Control的父级的CrossThread异常

时间:2018-03-19 23:19:48

标签: c# multithreading exception thread-safety cross-thread

TabControl _tabControl;
TabPage _tabPage;
ListView _listView;

///
this._tabControl.Controls.Add(this._tabPage);
this._tabPage.Controls.Add(this._listView)
///

private void UpdateListView()
{
    If (_listView.InvokeRequired)
    {
        IAsyncResult _IAsyncResult = _listView.BeginInvoke(//...invoke method and parameters...//);

        While (!_IAsyncResult.IsCompleted) { Application.DoEvents(); }

        _listView.EndInvoke(_IAsyncResult);
    }
    else
        _listView.Items[0].SubItems[0].Text = "[some string]";
}

我从UI线程以外的线程调用UpdateListView()。 我在语句“_listView.BeginInvoke(//...//);”中得到了跨线程异常。并且为_tabControl引发了异常。

System.InvalidOperationException was unhandled
  HResult=-2146233079
  Message=Cross-thread operation not valid: Control '_tabControl' accessed from a thread other than the thread it was created on.
  Source=System.Windows.Forms
  StackTrace:
       at System.Windows.Forms.Control.get_Handle()
       at System.Windows.Forms.Control.MarshaledInvoke(Control caller, Delegate method, Object[] args, Boolean synchronous)
       at System.Windows.Forms.Control.BeginInvoke(Delegate method, Object[] args)
       at TestApp.frmMain_Sub.UpdateListView(ListView _lv, Int32 _itemIndex, Int32 _subItemIndex, String _txt) in C:\Test\TestApp\frmMain_Sub.cs:line 5536
       at TestApp.frmMain_Sub.UpdateStatus() in C:\Test\TestApp\frmMain_Sub.cs:line 5012
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

我该如何处理这种情况? 非常感谢谁能指引我完成这件事。

0 个答案:

没有答案