By CruelIO


2009-03-19 09:37:40 8 Comments

What is the simplest way to update a Label from another thread?

I have a Form on thread1, and from that I'm starting another thread (thread2). While thread2 is processing some files I would like to update a Label on the Form with the current status of thread2's work.

How can I do that?

30 comments

@Alex 2019-04-11 12:00:11

General approach is like:

using System;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        int clickCount = 0;

        public Form1()
        {
            InitializeComponent();
            label1.SetText("0");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            new Thread(() => label1.SetText((++clickCount).ToString())).Start();
        }
    }

    public static class ControlExtensions
    {
        public static void SetText(this Control control, string text)
        {
            if (control.InvokeRequired)
                control.Invoke(setText, control, text);
            else
                control.Text = text;
        }

        private static readonly Action<Control, string> setText =
            (control, text) => control.Text = text;
    }
}

Explanation:

The answer is pretty like this one. But uses neater (as for me) and newer syntax. The point is InvokeRequired property of control. It gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on. So if we call control.SetText("some text") on the same thread control was created on, it's OK just to set Text as this control.Text = text. But on any other thread it causes System.InvalidOperationException so one must call a method via control.Invoke(...) to set Text on the thread control was created on.

@Alex 2019-05-07 12:20:34

@Nico Haase, OK.

@user53373 2019-04-11 13:17:06

just use synchronization context of ui

using System.Threading;

// ...

public partial class MyForm : Form
{
    private readonly SynchronizationContext uiContext;

    public MyForm()
    {
        InitializeComponent();
        uiContext = SynchronizationContext.Current; // get ui thread context
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Thread t = new Thread(() =>
            {// set ui thread context to new thread context                            
             // for operations with ui elements to be performed in proper thread
             SynchronizationContext
                 .SetSynchronizationContext(uiContext);
             label1.Text = "some text";
            });
        t.Start();
    }
}

@user53373 2019-04-12 10:38:35

Sure thing. I've added comments for that purpose.

@user53373 2019-05-07 10:00:14

I'm not very good at threading.

@user53373 2019-05-07 10:01:03

But votes show my answer in not bad I see.

@user53373 2019-05-07 10:03:32

Thank you for attention to it.

@flodis 2018-11-17 21:40:04

And yet another generic Control extension aproach..

First add an extension method for objects of type Control

public static void InvokeIfRequired<T>(this T c, Action<T> action) where T : Control
{
    if (c.InvokeRequired)
    {
        c.Invoke(new Action(() => action(c)));
    }
    else
    {
        action(c);
    }
}

and call like this from another thread to access a Control named object1 in UI-thread:

object1.InvokeIfRequired(c => { c.Visible = true; });
object1.InvokeIfRequired(c => { c.Text = "ABC"; });

..or like this

object1.InvokeIfRequired(c => 
  { 
      c.Text = "ABC";
      c.Visible = true; 
  }
);

@Manohar Reddy Poreddy 2016-11-17 23:26:19

Most of the other answers are a little complex for me on this question (I'm new to C#), so I am writing mine:

I have a WPF application and have defined a worker as below:

Issue:

BackgroundWorker workerAllocator;
workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1) {
    // This is my DoWork function.
    // It is given as an anonymous function, instead of a separate DoWork function

    // I need to update a message to textbox (txtLog) from this thread function

    // Want to write below line, to update UI
    txt.Text = "my message"

    // But it fails with:
    //  'System.InvalidOperationException':
    //  "The calling thread cannot access this object because a different thread owns it"
}

Solution:

workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1)
{
    // The below single line works
    txtLog.Dispatcher.BeginInvoke((Action)(() => txtLog.Text = "my message"));
}

I am yet to find out what the above line means, but it works.

For WinForms:

Solution:

txtLog.Invoke((MethodInvoker)delegate
{
    txtLog.Text = "my message";
});

@Marc L. 2018-07-10 17:52:02

The question was about Winforms, not WPF.

@Manohar Reddy Poreddy 2018-07-11 04:12:41

Thanks. Added WinForms solution above.

@Marc L. 2018-07-11 13:52:09

...which is just a copy of however many other answers on this same question, but okay. Why not be part of the solution and just delete your answer?

@Manohar Reddy Poreddy 2018-07-11 15:51:15

hmm, correct you are, if only, you read my answer with attention, the beginning part (the reason why i wrote the answer), and hopefully with a little more attention you see there is someone who had exact same problem & upvoted today for my simple answer, and with even more attn if you could foresee the real story on why all this happened, that google sends me here even when i search for wpf. Sure since you missed these more or less obvious 3 reasons, i can understand why you won't remove your downvote. Instead of cleaning the okay one, create something new which is much more difficult.

@Lankan 2018-02-28 10:22:53

Simplest way is invoking as follows:

 Application.Current.Dispatcher.Invoke(new Action(() =>
             {
                    try
                    {
                        ///
                    }
                    catch (Exception)
                    {
                      //
                    }


                    }
     ));

@LarsTech 2018-02-28 19:51:01

Except that the question is for WinForms.

@siggi_pop 2018-11-14 12:32:38

Don't know why this was downvoted!? it help me with my issue in a WPF application. Not all readers of this post will have exactly same issue as OP, sometimes a part of the solution can help the reader in a shorter time, then a complete solution to a unique problem.

@Frederik Gheysels 2009-03-19 09:45:44

You'll have to make sure that the update happens on the correct thread; the UI thread.

In order to do this, you'll have to Invoke the event-handler instead of calling it directly.

You can do this by raising your event like this:

(The code is typed here out of my head, so I haven't checked for correct syntax, etc., but it should get you going.)

if( MyEvent != null )
{
   Delegate[] eventHandlers = MyEvent.GetInvocationList();

   foreach( Delegate d in eventHandlers )
   {
      // Check whether the target of the delegate implements 
      // ISynchronizeInvoke (Winforms controls do), and see
      // if a context-switch is required.
      ISynchronizeInvoke target = d.Target as ISynchronizeInvoke;

      if( target != null && target.InvokeRequired )
      {
         target.Invoke (d, ... );
      }
      else
      {
          d.DynamicInvoke ( ... );
      }
   }
}

Note that the code above will not work on WPF projects, since WPF controls do not implement the ISynchronizeInvoke interface.

In order to make sure that the code above works with Windows Forms and WPF, and all other platforms, you can have a look at the AsyncOperation, AsyncOperationManager and SynchronizationContext classes.

In order to easily raise events this way, I've created an extension method, which allows me to simplify raising an event by just calling:

MyEvent.Raise(this, EventArgs.Empty);

Of course, you can also make use of the BackGroundWorker class, which will abstract this matter for you.

@Frederik Gheysels 2009-03-19 09:51:40

Indeed, but I don't like to 'clutter' my GUI code with this matter. My GUI shouldn't care whether it needs to Invoke or not. In other words: i don't think that it is the responsability of the GUI to perform the context-swithc.

@Marc Gravell 2009-03-19 11:07:47

Breaking the delegate apart etc seems overkill - why not just: SynchronizationContext.Current.Send(delegate { MyEvent(...); }, null);

@Frederik Gheysels 2009-03-19 11:42:57

Do you always have access to the SynchronizationContext ? Even if your class is in a class lib ?

@Marc Gravell 2009-03-19 10:17:51

The simplest way is an anonymous method passed into Label.Invoke:

// Running on the worker thread
string newText = "abc";
form.Label.Invoke((MethodInvoker)delegate {
    // Running on the UI thread
    form.Label.Text = newText;
});
// Back on the worker thread

Notice that Invoke blocks execution until it completes--this is synchronous code. The question doesn't ask about asynchronous code, but there is lots of content on Stack Overflow about writing asynchronous code when you want to learn about it.

@Frederik Gheysels 2009-03-19 10:25:24

But, then your processing function must be a member method of your GUI form ?

@Marc Gravell 2009-03-19 10:30:38

Seeing as the OP hasn't mentioned any class/instance except the form, that isn't a bad default...

@AZ. 2010-03-16 19:49:15

Don't forget the "this" keyword is referencing a "Control" class.

@codecompleting 2011-12-01 16:33:05

@MarcGravell but don't you need to do 'if invokeRequired' first?

@Marc Gravell 2011-12-01 16:50:55

@codecompleting it is safe either way, and we already know we're on a worker, so why check something we know?

@Dragouf 2012-02-16 16:39:44

You should use InvokeRequired and the anonymous delegate at the begining of the method like it shown in Hatth answer

@Marc Gravell 2012-02-16 18:16:35

@Dragouf not really - one of the point of using this method is that you already know which parts run on the worker, and which run on the UI thread. No need to check.

@codingadventures 2013-12-11 17:48:30

@MarcGravell it's a brilliant solution, how did u find out using an anonymous method runs on the main thread?

@Marc Gravell 2013-12-11 19:40:36

@John because that is what Control.Invoke does with any delegate - not just anon methods

@Marc Gravell 2014-07-30 11:03:18

@Joan.bdm without a concrete example, it is impossible to comment; the code shown will not do that.

@Joan.bdm 2014-07-30 11:33:03

@MarcGravell you are right, i'm having the exception in this line: String validated = wsPr.validateBooking(iberostarbck.client.utils.IdConexion, dsNewBooking, ref errorTxt); which is a call to a webservice with parms (Decimal, DataSet, ref String). Any ideas?

@Marc Gravell 2014-07-30 12:00:31

@Joan.bdm there is nowhere near enough context for me to comment on that

@Traubenfuchs 2014-09-03 12:38:31

@MarcGravell Is there any (performance) difference in doing it your way compared to using "new MethodInvoker(()=>{someLabel.Text = newText;})

@MonsterMMORPG 2015-04-11 22:52:18

Hello are there anyway to fire an event when this invoke is run on ui thread and the thread value is updated ?

@jj_ 2015-11-22 14:12:41

Why with this solution performance is worse than Ryszard Dżegan solution(TAP pattern) ? I am genuinely asking because I'm new to C#

@ahmar 2012-10-24 06:38:45

When I encountered the same issue I sought help from Google, but rather than give me a simple solution it confused me more by giving examples of MethodInvoker and blah blah blah. So I decided to solve it on my own. Here is my solution:

Make a delegate like this:

Public delegate void LabelDelegate(string s);

void Updatelabel(string text)
{
   if (label.InvokeRequired)
   {
       LabelDelegate LDEL = new LabelDelegate(Updatelabel);
       label.Invoke(LDEL, text);
   }
   else
       label.Text = text
}

You can call this function in a new thread like this

Thread th = new Thread(() => Updatelabel("Hello World"));
th.start();

Don't be confused with Thread(() => .....). I use an anonymous function or lambda expression when I work on a thread. To reduce the lines of code you can use the ThreadStart(..) method too which I am not supposed to explain here.

@Saurabh 2017-03-25 04:40:40

Put some common variable in a separate class to hold the value.

Example:

public  class data_holder_for_controls
{
    // It will hold the value for your label
    public string status = string.Empty;
}

class Demo
{
    public static  data_holder_for_controls d1 = new data_holder_for_controls();

    static void Main(string[] args)
    {
        ThreadStart ts = new ThreadStart(perform_logic);
        Thread t1 = new Thread(ts);
        t1.Start();
        t1.Join();
        //your_label.Text=d1.status; --- can access it from any thread
    }

    public static void perform_logic()
    {
        // Put some code here in this function
        for (int i = 0; i < 10; i++)
        {
            // Statements here
        }
        // Set the result in the status variable
        d1.status = "Task done";
    }
}

@Alexander Egorov 2017-03-05 07:42:26

Another example about the subject: I made an abstract class, UiSynchronizeModel, that contains a common method implementation:

public abstract class UiSynchronizeModel
{
    private readonly TaskScheduler uiSyncContext;
    private readonly SynchronizationContext winformsOrDefaultContext;

    protected UiSynchronizeModel()
    {
        this.winformsOrDefaultContext = SynchronizationContext.Current ?? new SynchronizationContext();
        this.uiSyncContext = TaskScheduler.FromCurrentSynchronizationContext();
    }

    protected void RunOnGuiThread(Action action)
    {
        this.winformsOrDefaultContext.Post(o => action(), null);
    }

    protected void CompleteTask(Task task, TaskContinuationOptions options, Action<Task> action)
    {
        task.ContinueWith(delegate
        {
            action(task);
            task.Dispose();
        }, CancellationToken.None, options, this.uiSyncContext);
    }
}

Your model or controller class should be derived from this abstract class. You can use any pattern (tasks or manually managed background threads) and use these methods like this:

public void MethodThatCalledFromBackroundThread()
{
   this.RunOnGuiThread(() => {
       // Do something over UI controls
   });
}

Tasks example:

var task = Task.Factory.StartNew(delegate
{
    // Background code
    this.RunOnGuiThread(() => {
        // Do something over UI controls
    });
});

this.CompleteTask(task, TaskContinuationOptions.OnlyOnRanToCompletion, delegate
{
    // Code that can safely use UI controls
});

@Musculaa 2017-01-18 13:01:31

First get the instance of your form (in this case mainForm), and then just use this code in the another thread.

mainForm.Invoke(new MethodInvoker(delegate () 
{
    // Update things in my mainForm here
    mainForm.UpdateView();
}));

@Basheer AL-MOMANI 2016-06-27 11:31:35

The simplest way in WPF applications is:

this.Dispatcher.Invoke((Action)(() =>
{
    // This refers to a form in a WPF application 
    val1 = textBox.Text; // Access the UI 
}));

@Gulpener 2016-09-27 08:28:26

This is correct, if you are using a WPF application. But he is using Windows Forms.

@Francis 2019-04-10 06:39:28

You can use the Dispatcher even in a Winforms application. stackoverflow.com/questions/303116/…

@John Peters 2016-05-16 01:50:41

Here's a new look on an age-old issue using a more functional style. If you keep the TaskXM class in all of your projects you only have one line of code to never worry about cross-thread updates again.

public class Example
{
    /// <summary>
    /// No more delegates, background workers, etc. Just one line of code as shown below.
    /// Note it is dependent on the Task Extension method shown next.
    /// </summary>
    public async void Method1()
    {
        // Still on the GUI thread here if the method was called from the GUI thread
        // This code below calls the extension method which spins up a new task and calls back.
        await TaskXM.RunCodeAsync(() =>
        {
            // Running an asynchronous task here
            // Cannot update the GUI thread here, but can do lots of work
        });
        // Can update GUI on this line
    }
}


/// <summary>
/// A class containing extension methods for the Task class
/// </summary>
public static class TaskXM
{
    /// <summary>
    /// RunCodeAsyc is an extension method that encapsulates the Task.run using a callback
    /// </summary>
    /// <param name="Code">The caller is called back on the new Task (on a different thread)</param>
    /// <returns></returns>
    public async static Task RunCodeAsync(Action Code)
    {
        await Task.Run(() =>
        {
            Code();
        });
        return;
    }
}

@Marc L. 2018-07-10 20:33:49

Really asking: how does wrapping Task.Run like this differ from just calling await Task.Run(() => {...});? What is the advantage of the indirection here?

@John Peters 2018-07-11 00:25:21

Superficially no difference. Looking deeper, it shows the power of functional programming. In particular it is wrapping a static method which aids in single responsibility. What if you now wanted to implement ConfigureAwait(false) or add a logging statement. You can now do it just once.

@MBH 2015-12-19 09:27:10

I couldn't get Microsoft's logic behind this ugly implementation, but you have to have two functions:

void setEnableLoginButton()
{
  if (InvokeRequired)
  {
    // btn_login can be any conroller, (label, button textbox ..etc.)

    btn_login.Invoke(new MethodInvoker(setEnable));

    // OR
    //Invoke(new MethodInvoker(setEnable));
  }
  else {
    setEnable();
  }
}

void setEnable()
{
  btn_login.Enabled = isLoginBtnEnabled;
}

These snippets work for me, so I can do something on another thread, and then I update the GUI:

Task.Factory.StartNew(()=>
{
    // THIS IS NOT GUI
    Thread.Sleep(5000);
    // HERE IS INVOKING GUI
    btn_login.Invoke(new Action(() => DoSomethingOnGUI()));
});

private void DoSomethingOnGUI()
{
   // GUI
   MessageBox.Show("message", "title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}

Even simpler:

btn_login.Invoke(new Action(()=>{ /* HERE YOU ARE ON GUI */ }));

@Roman Ambinder 2015-01-31 13:33:05

Basically the way to resolve this issue regardless of the framework version or the GUI underlying library type is to save the control creating the thread's Synchronization context for the worker thread that will marshal the control's related interaction from the worker thread to the GUI's thread messages queue.

Example:

SynchronizationContext ctx = SynchronizationContext.Current; // From control
ctx.Send\Post... // From worker thread

@Sume 2014-11-06 15:39:59

I just read the answers and this appears to be a very hot topic. I'm currently using .NET 3.5 SP1 and Windows Forms.

The well-known formula greatly described in the previous answers that makes use of the InvokeRequired property covers most of the cases, but not the entire pool.

What if the Handle has not been created yet?

The InvokeRequired property, as described here (Control.InvokeRequired Property reference to MSDN) returns true if the call was made from a thread that is not the GUI thread, false either if the call was made from the GUI thread, or if the Handle was not created yet.

You can come across an exception if you want to have a modal form shown and updated by another thread. Because you want that form shown modally, you could do the following:

private MyForm _gui;

public void StartToDoThings()
{
    _gui = new MyForm();
    Thread thread = new Thread(SomeDelegate);
    thread.Start();
    _gui.ShowDialog();
}

And the delegate can update a Label on the GUI:

private void SomeDelegate()
{
    // Operations that can take a variable amount of time, even no time
    //... then you update the GUI
    if(_gui.InvokeRequired)
        _gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
    else
        _gui.Label1.Text = "Done!";
}

This can cause an InvalidOperationException if the operations before the label's update "take less time" (read it and interpret it as a simplification) than the time it takes for the GUI thread to create the Form's Handle. This happens within the ShowDialog() method.

You should also check for the Handle like this:

private void SomeDelegate()
{
    // Operations that can take a variable amount of time, even no time
    //... then you update the GUI
    if(_gui.IsHandleCreated)  //  <---- ADDED
        if(_gui.InvokeRequired)
            _gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
        else
            _gui.Label1.Text = "Done!";
}

You can handle the operation to perform if the Handle has not been created yet: You can just ignore the GUI update (like shown in the code above) or you can wait (more risky). This should answer the question.

Optional stuff: Personally I came up coding the following:

public class ThreadSafeGuiCommand
{
  private const int SLEEPING_STEP = 100;
  private readonly int _totalTimeout;
  private int _timeout;

  public ThreadSafeGuiCommand(int totalTimeout)
  {
    _totalTimeout = totalTimeout;
  }

  public void Execute(Form form, Action guiCommand)
  {
    _timeout = _totalTimeout;
    while (!form.IsHandleCreated)
    {
      if (_timeout <= 0) return;

      Thread.Sleep(SLEEPING_STEP);
      _timeout -= SLEEPING_STEP;
    }

    if (form.InvokeRequired)
      form.Invoke(guiCommand);
    else
      guiCommand();
  }
}

I feed my forms that get updated by another thread with an instance of this ThreadSafeGuiCommand, and I define methods that update the GUI (in my Form) like this:

public void SetLabeTextTo(string value)
{
  _threadSafeGuiCommand.Execute(this, delegate { Label1.Text = value; });
}

In this way I'm quite sure that I will have my GUI updated whatever thread will make the call, optionally waiting for a well-defined amount of time (the timeout).

@Jon 2016-02-11 18:04:31

Came here to find this, as I also check for IsHandleCreated. One other property to check is IsDisposed. If your form is disposed, you cannot call Invoke() on it. If the user closed the form before your background thread could complete you don't want it trying to call back to the UI when the form is disposed.

@Phil1970 2016-12-18 15:00:47

I would say that it is a bad idea to start with... Normally, you would show the child form immediately and have a progress bar or some other feedback while doing background processing. Or you would do all processing first and then pass the result to the new form at creation. Doing both at the same time would generally have marginal benefits but much less maintainable code.

@Sume 2017-03-30 13:42:38

The described scenario takes into account a modal form used as a progress view of a background-thread job. Because it must be modal, it must be shown by calling the Form.ShowDialog() method. By doing this, you prevent your code that follows the call to be executed until the form is closed. So, unless you can start the background thread differently from the given example (and, of course, you can) this form must be modally shown after the background thread has started. In this case, you need to check for the Handle to be created. If you don't need a modal form, then it's another story.

@Sukhdevsinh Zala 2014-07-02 07:28:31

To achieve this in WPF I do it the following way.

 new Thread(() => 
 {
     while (...)
     {
         SomeLabel.Dispatcher.BeginInvoke((Action)(() => SomeLabel.Text = ...));
     }
 }).Start();

@Andrew Barber 2014-07-02 19:47:53

The question is actually about [winforms], by the way.

@nosalan 2014-05-11 18:43:31

When you're in the UI thread you could ask it for its synchronization context task scheduler. It would give you a TaskScheduler that schedules everything on the UI thread.

Then you can chain your tasks so that when the result is ready then another task (which is scheduled on the UI thread) picks it and assigns it to a label.

public partial class MyForm : Form
{
  private readonly TaskScheduler _uiTaskScheduler;
  public MyForm()
  {
    InitializeComponent();
    _uiTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();
  }

  private void buttonRunAsyncOperation_Click(object sender, EventArgs e)
  {
    RunAsyncOperation();
  }

  private void RunAsyncOperation()
  {
    var task = new Task<string>(LengthyComputation);
    task.ContinueWith(antecedent =>
                         UpdateResultLabel(antecedent.Result), _uiTaskScheduler);
    task.Start();
  }

  private string LengthyComputation()
  {
    Thread.Sleep(3000);
    return "47";
  }

  private void UpdateResultLabel(string text)
  {
    labelResult.Text = text;
  }
}

This works for tasks (not threads) which are the preferred way of writing concurrent code now.

@Ohad Schneider 2014-05-24 08:07:12

Calling Task.Start is typically not a good practice blogs.msdn.com/b/pfxteam/archive/2012/01/14/10256832.aspx

@Carsten R. 2014-05-01 11:29:36

Maybe a little bit overdose, but this is the kind of way I solve this normally:

Invokes are not required here because of the synchronization. The BasicClassThreadExample is just a kind of layout for me, so change it to fit your actual needs.

It is simple because you don't need to handle the stuff in the UI thread!

public partial class Form1 : Form
{
    BasicClassThreadExample _example;

    public Form1()
    {
        InitializeComponent();
        _example = new BasicClassThreadExample();
        _example.MessageReceivedEvent += _example_MessageReceivedEvent;
    }

    void _example_MessageReceivedEvent(string command)
    {
        listBox1.Items.Add(command);
    }

    private void button1_Click(object sender, EventArgs e)
    {
        listBox1.Items.Clear();
        _example.Start();
    }
}

public class BasicClassThreadExample : IDisposable
{
    public delegate void MessageReceivedHandler(string msg);

    public event MessageReceivedHandler MessageReceivedEvent;

    protected virtual void OnMessageReceivedEvent(string msg)
    {
        MessageReceivedHandler handler = MessageReceivedEvent;
        if (handler != null)
        {
            handler(msg);
        }
    }

    private System.Threading.SynchronizationContext _SynchronizationContext;
    private System.Threading.Thread _doWorkThread;
    private bool disposed = false;

    public BasicClassThreadExample()
    {
        _SynchronizationContext = System.ComponentModel.AsyncOperationManager.SynchronizationContext;
    }

    public void Start()
    {
        _doWorkThread = _doWorkThread ?? new System.Threading.Thread(dowork);

        if (!(_doWorkThread.IsAlive))
        {
            _doWorkThread = new System.Threading.Thread(dowork);
            _doWorkThread.IsBackground = true;
            _doWorkThread.Start();
        }
    }

    public void dowork()
    {
        string[] retval = System.IO.Directory.GetFiles(@"C:\Windows\System32", "*.*", System.IO.SearchOption.TopDirectoryOnly);
        foreach (var item in retval)
        {
            System.Threading.Thread.Sleep(25);
            _SynchronizationContext.Post(new System.Threading.SendOrPostCallback(delegate(object obj)
            {
                OnMessageReceivedEvent(item);
            }), null);
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                _doWorkThread.Abort();
            }
            disposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~BasicClassThreadExample() { Dispose(false); }

}

@Da Xiong 2014-03-19 06:27:14

For example, access a control other than in the current thread:

Speed_Threshold = 30;
textOutput.Invoke(new EventHandler(delegate
{
    lblThreshold.Text = Speed_Threshold.ToString();
}));

There the lblThreshold is a Label and Speed_Threshold is a global variable.

@blackmind 2014-02-19 17:36:56

Create a class variable:

SynchronizationContext _context;

Set it in the constructor that creates your UI:

var _context = SynchronizationContext.Current;

When you want to update the label:

_context.Send(status =>{
    // UPDATE LABEL
}, null);

@Jon H 2013-05-31 11:12:53

None of the Invoke stuff in the previous answers is necessary.

You need to look at WindowsFormsSynchronizationContext:

// In the main thread
WindowsFormsSynchronizationContext mUiContext = new WindowsFormsSynchronizationContext();

...

// In some non-UI Thread

// Causes an update in the GUI thread.
mUiContext.Post(UpdateGUI, userData);

...

void UpdateGUI(object userData)
{
    // Update your GUI controls here
}

@increddibelly 2016-05-05 09:09:23

what do you think the Post method uses under the hood? :)

@Embedd_Khurja 2012-07-27 23:08:45

You may use the already-existing delegate Action:

private void UpdateMethod()
{
    if (InvokeRequired)
    {
        Invoke(new Action(UpdateMethod));
    }
}

@MajesticRa 2012-02-22 13:01:42

My version is to insert one line of recursive "mantra":

For no arguments:

    void Aaaaaaa()
    {
        if (InvokeRequired) { Invoke(new Action(Aaaaaaa)); return; } //1 line of mantra

        // Your code!
    }

For a function that has arguments:

    void Bbb(int x, string text)
    {
        if (InvokeRequired) { Invoke(new Action<int, string>(Bbb), new[] { x, text }); return; }
        // Your code!
    }

THAT is IT.


Some argumentation: Usually it is bad for code readability to put {} after an if () statement in one line. But in this case it is routine all-the-same "mantra". It doesn't break code readability if this method is consistent over the project. And it saves your code from littering (one line of code instead of five).

As you see if(InvokeRequired) {something long} you just know "this function is safe to call from another thread".

@bgmCoder 2011-12-17 19:51:54

Salvete! Having searched for this question, I found the answers by FrankG and Oregon Ghost to be the easiest most useful to me. Now, I code in Visual Basic and ran this snippet through a convertor; so I'm not sure quite how it turns out.

I have a dialog form called form_Diagnostics, which has a richtext box, called updateDiagWindow, which I am using as a sort of logging display. I needed to be able to update its text from all threads. The extra lines allow the window to automatically scroll to the newest lines.

And so, I can now update the display with one line, from anywhere in the entire program in the manner which you think it would work without any threading:

  form_Diagnostics.updateDiagWindow(whatmessage);

Main Code (put this inside of your form's class code):

#region "---------Update Diag Window Text------------------------------------"
// This sub allows the diag window to be updated by all threads
public void updateDiagWindow(string whatmessage)
{
    var _with1 = diagwindow;
    if (_with1.InvokeRequired) {
        _with1.Invoke(new UpdateDiagDelegate(UpdateDiag), whatmessage);
    } else {
        UpdateDiag(whatmessage);
    }
}
// This next line makes the private UpdateDiagWindow available to all threads
private delegate void UpdateDiagDelegate(string whatmessage);
private void UpdateDiag(string whatmessage)
{
    var _with2 = diagwindow;
    _with2.appendtext(whatmessage);
    _with2.SelectionStart = _with2.Text.Length;
    _with2.ScrollToCaret();
}
#endregion

@Francis 2011-03-02 06:59:59

This one is similar to the solution above using .NET Framework 3.0, but it solved the issue of compile-time safety support.

public  static class ControlExtension
{
    delegate void SetPropertyValueHandler<TResult>(Control souce, Expression<Func<Control, TResult>> selector, TResult value);

    public static void SetPropertyValue<TResult>(this Control source, Expression<Func<Control, TResult>> selector, TResult value)
    {
        if (source.InvokeRequired)
        {
            var del = new SetPropertyValueHandler<TResult>(SetPropertyValue);
            source.Invoke(del, new object[]{ source, selector, value});
        }
        else
        {
            var propInfo = ((MemberExpression)selector.Body).Member as PropertyInfo;
            propInfo.SetValue(source, value, null);
        }
    }
}

To use:

this.lblTimeDisplay.SetPropertyValue(a => a.Text, "some string");
this.lblTimeDisplay.SetPropertyValue(a => a.Visible, false);

The compiler will fail if the user passes the wrong data type.

this.lblTimeDisplay.SetPropertyValue(a => a.Visible, "sometext");

@Brian Gideon 2010-08-24 13:45:22

Because of the triviality of the scenario I would actually have the UI thread poll for the status. I think you will find that it can be quite elegant.

public class MyForm : Form
{
  private volatile string m_Text = "";
  private System.Timers.Timer m_Timer;

  private MyForm()
  {
    m_Timer = new System.Timers.Timer();
    m_Timer.SynchronizingObject = this;
    m_Timer.Interval = 1000;
    m_Timer.Elapsed += (s, a) => { MyProgressLabel.Text = m_Text; };
    m_Timer.Start();
    var thread = new Thread(WorkerThread);
    thread.Start();
  }

  private void WorkerThread()
  {
    while (...)
    {
      // Periodically publish progress information.
      m_Text = "Still working...";
    }
  }
}

The approach avoids the marshaling operation required when using the ISynchronizeInvoke.Invoke and ISynchronizeInvoke.BeginInvoke methods. There is nothing wrong with using the marshaling technique, but there are a couple of caveats you need to be aware of.

  • Make sure you do not call BeginInvoke too frequently or it could overrun the message pump.
  • Calling Invoke on the worker thread is a blocking call. It will temporarily halt the work being done in that thread.

The strategy I propose in this answer reverses the communication roles of the threads. Instead of the worker thread pushing the data the UI thread polls for it. This a common pattern used in many scenarios. Since all you are wanting to do is display progress information from the worker thread then I think you will find that this solution is a great alternative to the marshaling solution. It has the following advantages.

  • The UI and worker threads remain loosely coupled as opposed to the Control.Invoke or Control.BeginInvoke approach which tightly couples them.
  • The UI thread will not impede the progress of the worker thread.
  • The worker thread cannot dominate the time the UI thread spends updating.
  • The intervals at which the UI and worker threads perform operations can remain independent.
  • The worker thread cannot overrun the UI thread's message pump.
  • The UI thread gets to dictate when and how often the UI gets updated.

@Matt 2013-11-11 10:24:59

Good idea. The only thing you didn't mention is how you properly dispose the timer once the WorkerThread is finished. Note this can cause trouble when the application ends (i.e. the user closes the application). Do you have an idea how to solve this?

@Phil1970 2018-04-20 00:54:08

@Matt Instead of using an anonymous handler for Elapsed event, you use a member method so you can remove the timer when the form is disposed...

@Matt 2018-04-20 08:37:29

@Phil1970 - Good point. You meant like System.Timers.ElapsedEventHandler handler = (s, a) => { MyProgressLabel.Text = m_Text; }; and assigning it via m_Timer.Elapsed += handler;, later in the dispose context doing a m_Timer.Elapsed -= handler; am I right? And for the disposing/closing following the advice as discussed here.

@Hath 2009-03-19 10:31:21

This is the classic way you should do this:

using System;
using System.Windows.Forms;
using System.Threading;

namespace Test
{
    public partial class UIThread : Form
    {
        Worker worker;

        Thread workerThread;

        public UIThread()
        {
            InitializeComponent();

            worker = new Worker();
            worker.ProgressChanged += new EventHandler<ProgressChangedArgs>(OnWorkerProgressChanged);
            workerThread = new Thread(new ThreadStart(worker.StartWork));
            workerThread.Start();
        }

        private void OnWorkerProgressChanged(object sender, ProgressChangedArgs e)
        {
            // Cross thread - so you don't get the cross-threading exception
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    OnWorkerProgressChanged(sender, e);
                });
                return;
            }

            // Change control
            this.label1.Text = e.Progress;
        }
    }

    public class Worker
    {
        public event EventHandler<ProgressChangedArgs> ProgressChanged;

        protected void OnProgressChanged(ProgressChangedArgs e)
        {
            if(ProgressChanged!=null)
            {
                ProgressChanged(this,e);
            }
        }

        public void StartWork()
        {
            Thread.Sleep(100);
            OnProgressChanged(new ProgressChangedArgs("Progress Changed"));
            Thread.Sleep(100);
        }
    }


    public class ProgressChangedArgs : EventArgs
    {
        public string Progress {get;private set;}
        public ProgressChangedArgs(string progress)
        {
            Progress = progress;
        }
    }
}

Your worker thread has an event. Your UI thread starts off another thread to do the work and hooks up that worker event so you can display the state of the worker thread.

Then in the UI you need to cross threads to change the actual control... like a label or a progress bar.

@ILoveFortran 2012-05-28 00:23:38

Label lblText; //initialized elsewhere

void AssignLabel(string text)
{
   if (InvokeRequired)
   {
      BeginInvoke((Action<string>)AssignLabel, text);
      return;
   }

   lblText.Text = text;           
}

Note that BeginInvoke() is preferred over Invoke() because it's less likely to cause deadlocks (however, this is not an issue here when just assigning text to a label):

When using Invoke() you are waiting for the method to return. Now, it may be that you do something in the invoked code that will need to wait for the thread, which may not be immediately obvious if it's buried in some functions that you are calling, which itself may happen indirectly via event handlers. So you would be waiting for the thread, the thread would be waiting for you and you are deadlocked.

This actually caused some of our released software to hang. It was easy enough to fix by replacing Invoke() with BeginInvoke(). Unless you have a need for synchronous operation, which may be the case if you need a return value, use BeginInvoke().

@user523650 2014-01-27 13:39:27

I prefer this one:

private void UpdateNowProcessing(string nowProcessing)
{
    if (this.InvokeRequired)
    {
        Action<string> d = UpdateNowProcessing;
        Invoke(d, nowProcessing);
    }
    else
    {
        this.progressDialog.Next(nowProcessing);
    }            
}

Related Questions

Sponsored Content

24 Answered Questions

[SOLVED] Reading settings from app.config or web.config in .NET

19 Answered Questions

[SOLVED] How to use threading in Python?

18 Answered Questions

[SOLVED] Is there a way to check if a file is in use?

42 Answered Questions

[SOLVED] "implements Runnable" vs "extends Thread" in Java

34 Answered Questions

[SOLVED] What is the difference between a process and a thread?

27 Answered Questions

[SOLVED] How to enumerate an enum?

26 Answered Questions

[SOLVED] Why not inherit from List<T>?

28 Answered Questions

[SOLVED] How do I get the path of the assembly the code is in?

  • 2008-09-09 20:12:28
  • George Mauer
  • 579507 View
  • 745 Score
  • 28 Answer
  • Tags:   c# .net reflection

39 Answered Questions

21 Answered Questions

Sponsored Content