Accessing a form's control from a separate thread

后端 未结 5 437
Happy的楠姐
Happy的楠姐 2020-11-30 10:57

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,

相关标签:
5条回答
  • 2020-11-30 11:46

    The UI elements can only be accessed by the UI thread. WinForms and WPF/Silverlight doesn't allow access to controls from multiple threads.

    A work-around to this limitation can be found here.

    0 讨论(0)
  • 2020-11-30 11:46

    A Control can only be accessed within the thread that created it - the UI thread.

    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.

    0 讨论(0)
  • 2020-11-30 11:47

    You can check the Control.InvokeRequired flag and then use the Control.Invoke method if necessary. Control.Invoke takes a delegate so you can use the built-in Action<T>.

    public void UpdateProgress(int percentComplete)
    {
       if (!InvokeRequired)
       {
          ProgressBar.Value = percentComplete;
       }
       else
       {
          Invoke(new Action<int>(UpdateProgress), percentComplete);
       }
    }
    
    0 讨论(0)
  • 2020-11-30 11:51
     private void Form1_Load(object sender, EventArgs e)
        {
            CheckForIllegalCrossThreadCalls = false;
        }
    

    Maybe this will work.

    0 讨论(0)
  • 2020-11-30 11:56

    You need to call method Invoke from non-UI threads to perform some actions on form and other controls.

    0 讨论(0)
提交回复
热议问题