[c#] Invoke(Delegate)

Can anybody please explain this statement written on this link

Invoke(Delegate):

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

Can anybody explain what this means (especially the bold one) I am not able to get it clearly

This question is related to c# winforms delegates invoke

The answer is


Invoke((MethodInvoker)delegate{ textBox1.Text = "Test"; });

A control or window object in Windows Forms is just a wrapper around a Win32 window identified by a handle (sometimes called HWND). Most things you do with the control will eventually result in a Win32 API call that uses this handle. The handle is owned by the thread that created it (typically the main thread), and shouldn't be manipulated by another thread. If for some reason you need to do something with the control from another thread, you can use Invoke to ask the main thread to do it on your behalf.

For instance, if you want to change the text of a label from a worker thread, you can do something like this:

theLabel.Invoke(new Action(() => theLabel.Text = "hello world from worker thread!"));

It means that the delegate will run on the UI thread, even if you call that method from a background worker or thread-pool thread. UI elements have thread affinity - they only like talking directly to one thread: the UI thread. The UI thread is defined as the thread that created the control instance, and is therefore associated with the window handle. But all of that is an implementation detail.

The key point is: you would call this method from a worker thread so that you can access the UI (to change the value in a label, etc) - since you are not allowed to do that from any other thread than the UI thread.


If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).

In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created

private void btn_Click(object sender, EvenetArgs e)
{
    var thread1 = new Thread(SetText1);
    var thread2 = new Thread(SetText2);
    thread1.Start();
    thread2.Start();
}

private void SetText1() 
{
    textBox1.Text = "Test";
}

private void SetText2() 
{
    textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
}

Delegate are essentially inline Action's or Func<T>. You can declare a delegate outside the scope of a method which you are running or using a lambda expression(=>); because you run the delegate within a method, you run it on the thread which is being run for the current window/application which is the bit in bold.

Lambda example

int AddFiveToNumber(int number)
{
  var d = (int i => i + 5);
  d.Invoke(number);
}

In practical terms it means that the delegate is guaranteed to be invoked on the main thread. This is important because in the case of windows controls if you don't update their properties on the main thread then you either don't see the change, or the control raises an exception.

The pattern is:

void OnEvent(object sender, EventArgs e)
{
   if (this.InvokeRequired)
   {
       this.Invoke(() => this.OnEvent(sender, e);
       return;
   }

   // do stuff (now you know you are on the main thread)
}

this.Invoke(delegate) make sure that you are calling the delegate the argument to this.Invoke() on main thread/created thread.

I can say a Thumb rule don't access your form controls except from main thread.

May be the following lines make sense for using Invoke()

    private void SetText(string text)
    {
        // InvokeRequired required compares the thread ID of the
        // calling thread to the thread ID of the creating thread.
        // If these threads are different, it returns true.
        if (this.textBox1.InvokeRequired)
        {   
            SetTextCallback d = new SetTextCallback(SetText);
            this.Invoke(d, new object[] { text });
        }
        else
        {
            this.textBox1.Text = text;
        }
    }

There are situations though you create a Threadpool thread(i.e worker thread) it will run on main thread. It won't create a new thread coz main thread is available for processing further instructions. So First investigate whether the current running thread is main thread using this.InvokeRequired if returns true the current code is running on worker thread so call this.Invoke(d, new object[] { text });

else directly update the UI control(Here you are guaranteed that you are running the code on main thread.)


It means that the delegate you pass is executed on the thread that created the Control object (which is the UI thread).

You need to call this method when your application is multi-threaded and you want do some UI operation from a thread other than the UI thread, because if you just try to call a method on a Control from a different thread you'll get a System.InvalidOperationException.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager

Examples related to delegates

Delegates in swift? How can I make a weak protocol reference in 'pure' Swift (without @objc) C# cannot convert method to non delegate type Invoke(Delegate) What is a C++ delegate? How do I set up a simple delegate to communicate between two view controllers? LINQ where clause with lambda expression having OR clauses and null values returning incomplete results C# - using List<T>.Find() with custom objects Func vs. Action vs. Predicate What is Func, how and when is it used

Examples related to invoke

Invoke(Delegate) Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on What could cause java.lang.reflect.InvocationTargetException? Reflection: How to Invoke Method with parameters What's the difference between Invoke() and BeginInvoke() How do I invoke a Java method when given the method name as a string? Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on