WinForms interthread modification

前端 未结 4 1818
傲寒
傲寒 2020-12-21 13:46

Whenever I want to modify a winform from another thread, I need to use

->Invoke(delegate, params)

so that the modification occurs in the winf

4条回答
  •  青春惊慌失措
    2020-12-21 13:59

    The answer of Michael Meadows is a good example of how to centralize logic of updating a GUI form.

    Concerning performance (which we can easily become obsessed over) of invoking numerous delegates to synchronize the front end, a while ago, I wrote software that outperformed an equivalent C++ (native) windows application in terms of GUI synchronization! And that was all thanks to BeginInvoke and the ThreadPool class.

    Using Action<> and Func<> delegates and the ThreadPool class are beneficial too and consider the general Invoke pattern (exposed by Michael above):

    public void TheGuiInvokeMethod(Control source, string text)
    {
       if (InvokeRequired)
          Invoke(new Action(TheGuiInvokeMethod, source, text);
       else
       {
           // it is safe to update the GUI using the control
          control.Text = text;
       }
    }
    

    where TheGuiInvokeMethod would really be located in a form or other control.

提交回复
热议问题