如何在c#thread中设置visible值为true?

时间:2015-07-22 07:37:18

标签: c# multithreading winforms

我是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
}


怎么解决这个问题?

2 个答案:

答案 0 :(得分:4)

您无法访问其他线程中的UI元素。

对于Winforms: How to update the GUI from another thread in C#?

对于WPF: Change WPF controls from a non-main thread using Dispatcher.Invoke

chart1.Dispatcher.Invoke(() =>chart1.Visible = true);

答案 1 :(得分:0)

将您的Dowork方法签名更改为接受object作为参数,并将Synchronization上下文传递给它:

    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);