Reputation: 10730
I have a situation like this.
Submit button runs by a thread (say thread 1 ) and starts the operation. Is is this thread which updates the status property from the BL
Timer control creates a new thread each time to run the TimerEvent (Say thread 2 , 3 etc).
Issue here is that test.Status property , which is updated by thread1 is not accessible by other thread.. It is always null , even though the property has been updated by thread 1..
What is the solution for this ? Thanks in advance
public class TestClass //---->#1
{
private test = new Test() ; //---->#2
protected void SubmitButon_Click(object sender, EventArgs e)
{
// This is performed by Thread1
test.DoSomeThing() //------>#3
}
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
// Timer controls sends out a new thread each time
Label1.Text = test.Status; //------>#4
}
}
Upvotes: 0
Views: 833
Reputation: 10730
Issue happens because a new instance is created by the timerthread eachtime after as Line #2 is executed..Hence test.Status is always null.. That was the reason for the issue
Upvotes: 1
Reputation: 1585
here's sample to use delegate and update UI ements from different thread
delegate string CallFunctionDelegate(string arg1, string arg2);
private void btnStart_Click(object sender, EventArgs e)
{
CallFunctionDelegate delegRunApps = new CallFunctionDelegate(DoSomeThingBig);
AsyncCallback CallBackAfterAsynOperation = new AsyncCallback(AfterDoingSomethingBig);
delegRunApps.BeginInvoke("", "", CallBackAfterAsynOperation, null);
}
private string DoSomeThingBig(string arg1, string arg2)
{
#region Implemetation of time consuming function
//Implemetation of time consuming function
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
if (btnStart.InvokeRequired)
{
btnStart.Invoke((new MethodInvoker(delegate { btnStart.Text = i.ToString(); })));
}
else
{
btnStart.Text = i.ToString();
}
}
#endregion
return arg1.Replace("freetime", arg2);
}
private void AfterDoingSomethingBig(IAsyncResult result)
{
MessageBox.Show("Finaly Done!! ;) ");
btnStart.Invoke((new MethodInvoker(delegate { btnStart.Text = "Start"; })));
}
Upvotes: 1