我有一个带有一些控件的窗体.其中一个控件是文本框,另一个是listView.我还有一个按钮(上传),根据所选项目ListView对象上传文件.
为了报告上传进度%,我添加了一个进度条,通过联系服务器创建了一个可以上传文件的后台工作线程.如果没有创建后台工作程序的方法,进度条不会正确更新并且看起来没有响应.
现在,在上传文件时,我需要从ListView中获取选择并根据该选择获取文件.但是当我尝试从后台工作线程访问"ListView"时,我得到一个异常:System.InvalidOperationException:跨线程操作无效:
我该怎么做才能纠正这个例外?
在这种情况下,您的处理线程想要访问您的UI线程.
例:
private delegate void UpdateTextDelegate(object value);
private void UpdateText(object value)
{
if (this.textbox.InvokeRequired)
{
// This is a worker thread so delegate the task.
this.textbox.Invoke(new UpdateTextDelegate(this.UpdateText), value);
}
else
{
// This is the UI thread so perform the task.
this.textbox.Text = value.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)