【问题标题】:How can i set visible to true value in c# thread?如何在 c# 线程中将可见设置为真值?
【发布时间】:2015-07-22 07:37:17
【问题描述】:

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


怎么解决?

【问题讨论】:

  • 这是什么项目? Windows 窗体、WPF、Asp.Net ?请在此处提供更多代码。您的“启动新线程的代码”在哪里?
  • Windows 窗体,不好意思忘记了
  • chart1 是 UI 元素吗?

标签: c# multithreading winforms


【解决方案1】:

您无权从其他线程访问 UI 元素。

对于 Winform: 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);

【讨论】:

  • 如果他正在试图从另一个线程访问 UI 元素,他应该会抛出异常。我认为他没有提到...
  • 确实如此,但就你所知,他可以得到一个被静默处理的异常。
【解决方案2】:

更改您的 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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    • 2016-12-27
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多