Why using Action in this code? Why using Action in this code? multithreading multithreading

Why using Action in this code?


Because this code runs on a different thread from the UI and must be marshalled across to the UI thread with Invoke.

The documentation for Control.Invoke() states:

Executes the specified delegate on the thread that owns the control's underlying window handle.

This is all necessary because the underlying Windows framework requires that operations on a window handle are performed by the thread that owns the window handle.


If UpdateMessage is called from another thread you need to Invoke into main thread in order to interact with GUI elements

If you use just txtMessage.Text = message you will get CrossThreadOperationException


You should work with a control's properties in the UI thread, otherwise you will receive exception.

Control.Invoke() will execute your delegate by sending windows message to the window message loop.

But you can optimize code to prevent unnecessary thread syncronization when it don't required:

void UpdateMessage (string message){    if(InvokeRequired)    {        Invoke((Action)()=>UpdateMessage(message));        return;    }    txtMessage.Text = message;}