【问题标题】:Calling a method from a backgroundworker从后台工作人员调用方法
【发布时间】:2017-03-22 03:16:30
【问题描述】:

我有一个后台工作者,它在 DoWork 事件。

此方法访问 UI 线程中的数据集,它还调用 UI 线程中的另一个方法。

当方法需要访问 Ui 线程中存在的数据集和方法时,我的问题出现了,我得到一个跨线程操作无效错误。

如何访问项目 UI 线程? 我是否可以使用 backgroundworker 访问它,或者我必须使用其他方法在后台线程中运行我的方法

谢谢

【问题讨论】:

    标签: c# c#-3.0


    【解决方案1】:

    您只需将方法调用编组到 UI 线程。
    在 WinForms 上:

    void DoWork(...)
    {
        YourMethod();
    }
    
    void YourMethod()
    {
        if(yourControl.InvokeRequired)
            yourControl.Invoke((Action)(() => YourMethod()));
        else
        {
            //Access controls
        }
    }
    

    【讨论】:

      【解决方案2】:

      你应该使用 Dispatcher.Invoke 方法

      欲了解更多信息,请查看以下链接

      http://msdn.microsoft.com/en-us/library/system.windows.threading.dispatcher.invoke.aspx

      【讨论】:

        【解决方案3】:

        在 UI 线程中创建的控件不能以正常方式在另一个线程中访问。请创建一个委托并使用 control.Invoke 调用委托。

        下面提供的方法示例可用于启用按钮的可见性,无论您处于何种线程上下文中。

        private void EnableButtonVisibility( Button btn, bool enable)    
        {     
            if ( !btn.InvokeRequired )    
            {    
                btn.Visible = enable;    
            }   
            else    
            {    
                btn.Invoke( new EnableButtonVisibilityHandler( EnableButtonVisibility ), btn, enable );    
            }    
        }    
         delegate void EnableButtonVisibilityHandler( Button btn, bool enable);
        

        你也可以使用Action<Button, bool>实现同样的效果

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多