Alessandro Canicatti
Alessandro Canicatti

Reputation: 33

What does this instruction mean?

I'm using cefsharp to build a personal browser. Everything is fine but i've got a question for you.

What does this instruction mean? It is inserted in the main form. this.InvokeOnUiThreadIfRequired(() => urlTextBox.Text = browser.Address);

In the project i have also a Control static class which implements InvokeOnUiThreadIfRequired function.

public static void InvokeOnUiThreadIfRequired(this Control control, Action action)
{
    if (control.InvokeRequired)
    {
        control.BeginInvoke(action);
    }
    else
    {
        action.Invoke();
    }
}

So the questions are: - What does the form pass to the function? I don't understand the meaning of () =>. - What does the function receive as parameters?

Upvotes: 3

Views: 974

Answers (1)

Patrick Hofman
Patrick Hofman

Reputation: 156948

There a three interesting parts:

  1. InvokeOnUiThreadIfRequired: This code probably checks if the caller is on the UI thread. Since you are not allowed to change the UI from another thread than thr UI thread, this code is necessary.

  2. () => is a lambda expression following with the anonymous delegate (projected on an Action which is effectively a method with no parameters and no return value) to execute. In that way you can pass on a call to some code to another method.

  3. The InvokeOnUiThreadIfRequired method is an extension method. It allows you to 'attach' a method to an instance of another type which you don't own as it was a method of that class.

Upvotes: 13

Related Questions