异常“Cross-thread operation not valid: Control 'panelListView' accessed from a thread other than the thread it was created on.”
前言:我在搬砖的时候遇到了如下情形,在子窗口上有一个上传文件的按钮,上传文件比较耗时,所以我就开启了个线程去执行上传文件的逻辑,上传完成后刷新主窗口列表上传文件的状态,然后就抛出如下异常:
System.InvalidOperationException:“Cross-thread operation not valid: Control 'panelListView' accessed from a thread other than the thread it was created on.”
百度翻译了下:
就是我在子窗口调用刷新主窗口的方法出现了异常,
解决办法如下:
delegate void SearchDocumentInfoCallBack(); public void SearchDocumentInfo() { List<FrmMainSearchResultInfo> results = new List<FrmMainSearchResultInfo>(); if (panelListView.InvokeRequired) { SearchDocumentInfoCallBack callback = new SearchDocumentInfoCallBack(SearchDocumentInfo); this.Invoke(callback); } else { panelListView.DataSource = results; } }
其中:InvokeRequired的底层如下:
// // 摘要: // 获取一个值,该值指示调用方在对控件进行方法调用时是否必须调用 Invoke 方法,因为调用方位于创建控件所在的线程以外的线程中。 // // 返回结果: // 如果控件的 true 是在与调用线程不同的线程上创建的(说明您必须通过 Invoke 方法对控件进行调用),则为 System.Windows.Forms.Control.Handle;否则为 // false。 [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [EditorBrowsable(EditorBrowsableState.Advanced)] [SRDescriptionAttribute("ControlInvokeRequiredDescr")] public bool InvokeRequired { get; }
大致意思就是如果是在不同的线程上操作,需要Invoke方法进行调用,所以就定义了一个委托去回调当前方法,有点懵,大概是这个意思
编码中遇到了异常,记录下,后续再次遇到有个印象
不积跬步,无以至千里;不积小流,无以成江海。ヾ(◍°∇°◍)ノ゙