我是c#的初学者,我写了下面的代码来启动新的线程:
Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();
在up线程中处理一些东西并显示到图表中,一切都很好,但是当运行并完成DoWork
方法时,图表控件可视自动设置为false !,我的DoWork
方法是:
public void DoWork()
{
//.....some process and show into the process result into the chart
chart1.Visible = true;//this code not run
}
如何解决这个问题?
你不能从其他线程访问UI元素。
Winforms:如何从c#中的另一个线程更新GUI ?
WPF:使用Dispatcher从非主线程更改WPF控件。调用
chart1.Dispatcher.Invoke(() =>chart1.Visible = true);
更改Dowork方法签名以接受对象作为参数并传递同步上下文给它:
void DoWork(object o)
{
SynchronizationContext cont = o as SynchronizationContext;
// your logic gere
cont.Post(delegate
{
// all your UI updates here
}, null);
}
Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start(SynchronizationContext.Current);