[英]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.