我有这种情况。
提交按钮由一个线程(比如线程1)运行并开始操作。是这个线程从BL
更新状态属性Timer控件每次都会创建一个新线程来运行TimerEvent(比如线程2,3等)。
这里的问题是由thread1更新的test.Status属性是其他线程无法访问的。它始终为null,即使该属性已被线程1更新。
这是什么解决方案? 提前致谢
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
}
}
答案 0 :(得分:1)
这里是使用委托和更新来自不同线程的UI的示例
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"; })));
}
答案 1 :(得分:1)
问题发生是因为每次执行第2行后都会通过timethread创建一个新实例.Hence test.Status始终为null ..这就是问题的原因