[英]How can i set visible to true value in c# thread?
我是C#的新手,并且编写以下代码来启动新线程:
Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();
在上线程过程中有一些东西显示在图表中,每件事都可以,但是当运行并完成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.Invoke从非主线程更改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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.