[英]How can i set visible to true value in c# thread?
I'm beginner in c#,and i write this code for start the new thread: 我是C#的新手,并且编写以下代码来启动新线程:
Thread workerThread = new Thread(DoWork);
workerThread.Priority = ThreadPriority.Highest;
workerThread.Start();
in the up thread process some thing and show into the chart,every thing is okay,but when run and finish DoWork
method,chart control visible set to false automatically!,my DoWork
method is: 在上线程过程中有一些东西显示在图表中,每件事都可以,但是当运行并完成
DoWork
方法时,图表控件可见会自动设置为false !,我的DoWork
方法是:
public void DoWork()
{
//.....some process and show into the process result into the chart
chart1.Visible = true;//this code not run
}
how can solve that? 怎么解决呢?
You do not have access to UI elements from a different thread. 您无权从其他线程访问UI元素。
For Winforms: How to update the GUI from another thread in C#? 对于Winforms: 如何从C#中的另一个线程更新GUI?
For WPF: Change WPF controls from a non-main thread using Dispatcher.Invoke 对于WPF: 使用Dispatcher.Invoke从非主线程更改WPF控件
chart1.Dispatcher.Invoke(() =>chart1.Visible = true);
Change your Dowork method signature to accept object as parameter and pass Synchronization context to it: 更改您的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.