简体   繁体   English

从单独的线程访问表单的控件

[英]Accessing a form's control from a separate thread

I'm practising on threading and came across this problem. 我正在研究线程,并遇到了这个问题。 The situation is like this: 情况是这样的:

  1. I have 4 progress bars on a single form, one for downloading a file, one for showing the page loading status etc... 我在单个表单上有4个进度条,一个用于下载文件,一个用于显示页面加载状态等。

  2. I have to control the progress of each ProgressBar from a separate thread. 我必须从单独的线程控制每个ProgressBar的进度。

The problem is I'm getting an InvalidOperationException which says 问题是我收到一个InvalidOperationException ,它说

Cross-thread operation not valid: Control 'progressBar1' accessed from a thread other than the thread it was created on. 跨线程操作无效:从创建该线程的线程之外的其他线程访问控件'progressBar1'。

Am I wrong in this approach or can anybody tell me how to implement this? 我在这种方法上错了吗?或者有人可以告诉我如何实现吗?

A Control can only be accessed within the thread that created it - the UI thread. Control只能在创建它的线程(UI线程)中访问。

You would have to do something like: 您将必须执行以下操作:

Invoke(new Action(() =>
{
    progressBar1.Value = newValue;
}));

The invoke method then executes the given delegate, on the UI thread. 然后,invoke方法在UI线程上执行给定的委托。

You can check the Control.InvokeRequired flag and then use the Control.Invoke method if necessary. 您可以检查Control.InvokeRequired标志,然后在必要时使用Control.Invoke方法。 Control.Invoke takes a delegate so you can use the built-in Action<T>. Control.Invoke需要一个委托,因此您可以使用内置的Action <T>。

public void UpdateProgress(int percentComplete)
{
   if (!InvokeRequired)
   {
      ProgressBar.Value = percentComplete;
   }
   else
   {
      Invoke(new Action<int>(UpdateProgress), percentComplete);
   }
}

The UI elements can only be accessed by the UI thread. UI元素只能由UI线程访问。 WinForms and WPF/Silverlight doesn't allow access to controls from multiple threads. WinForms和WPF / Silverlight不允许从多个线程访问控件。

A work-around to this limitation can be found here . 可以在这里找到解决此限制的方法

 private void Form1_Load(object sender, EventArgs e)
    {
        CheckForIllegalCrossThreadCalls = false;
    }

Maybe this will work. 也许这会工作。

您需要从非UI线程调用方法Invoke,以对表单和其他控件执行一些操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM