【问题标题】:Access main thread control in backgroundworker thread在后台工作线程中访问主线程控制
【发布时间】:2013-10-03 07:04:28
【问题描述】:

我有一个函数 ShowPanel(Control ctrl) 需要将 Control 作为参数传递。 我需要在后台工作线程中调用这个函数。我使用以下代码

void bw_DoWork(object sender,DoWorkEventArgs e)
{                      
    ShowPanel(listBox1);           
}

但是执行失败

跨线程操作无效:控件“Form1”从 除了创建它的线程之外的线程

如何在后台线程中传递listBox1

【问题讨论】:

  • 如果在主界面创建listbox1,需要在backgroundworker的progresschangedevent中调用该函数。您需要从 doworkevents 调用 ReportProgress。

标签: c# multithreading winforms backgroundworker


【解决方案1】:

序列化调用,因为你不能访问在不同线程上创建的控件,你需要使用下面的序列化调用

 void bw_DoWork(object sender,DoWorkEventArgs e)
 {                      
   this.Invoke(new MethodInvoker(delegate {

              ShowPanel(listBox1);           
    })); 
 }

【讨论】:

  • 通过这样做,它没有给我任何例外,但仍然 ShowPanel(listBox1) 函数仅在主线程完成执行后调用
  • @rajeevkumar 确保您的线程在您从后台调用该方法时没有做其他事情或等待某事!如果是,它将在完成任务后执行 UI 代码
【解决方案2】:

我想应该有 BeginInvoke 而不是 Invoke。

否则这里有更通用的解决方案。

您需要添加对 WindowsBase.dll 的引用。

在主线程上获取线程的调度器:

public class SomeClass
{
    System.Windows.Threading.Dispatcher mainThreadDispatcher;       

    // assuming class is instantiated in a main thread, otherwise get a dispatcher to the
    // main thread
    public SomeClass()
    {
        Dispatcher mainThreadDispatcher = Dispatcher.CurrentDispatcher;
    }

    public void MethodCalledFromBackgroundThread()
    {
        mainThreadDispatcher.BeginInvoke((Action)({() => ShowPanel(listBox1);}));
    }
}

【讨论】:

  • Dispatcher 的东西也适用于 3.5,请参阅 msdn.microsoft.com/en-us/library/…
  • 但是在添加对 windowbase.dll 的引用时,它会给我以下警告 WindowBase.dll or one of its dependency required later version of .net framerwork than the one specified in the project ...
  • 好吧,我搞定了,但是你的 `mainThreadDispatcher.BeginInvoke((Action)() => ShowPanel(listBox1));` 的语法似乎是错误的。它没有编译。给出错误无效的表达式术语'('。无效的表达式术语'=>'
  • 我尝试了以下语法但结果相同,即 ShowPanel 仅在主线程完成后执行 mainThreadDispatcher.BeginInvoke(new MethodInvoker(delegate { ShowPanel(listBox); }));
  • 尝试编辑后的版本。我可能错过了一些括号,没有 Windows 机器来检查它是否编译
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多