0

How to ensure thread safety while updating some control from another thread?Can anybody help?

user42348
  • 4,181
  • 28
  • 69
  • 98
  • Duplicate of [ui-thread-safety](http://stackoverflow.com/questions/56886/ui-thread-safety) and lots of others – H H Sep 14 '10 at 09:53

2 Answers2

1

In WPF (see comments for details for WinForms): You'll want to invoke the dispatcher to execute your code on the UI thread: See MSDN here

If you don't you'll very quickly run into exceptions as the runtime won't let you update a UI component from a thread that didn't create it.

BeginInvoke is preferred over just Invoke as the former is asynchronous - you don't need to wait for the UI thread to be woken and the delegate invoked before the calling thread can continue - See this StackOverflow question

For example:

public delegate void myUIDelegate();

myButton.Dispatcher.BeginInvoke(
    DispatcherPriority.Normal,
    new myUIDelegate(() => {
       // Any code in this anonymous delegate is UI thread safe
       myButton.Enabled = true;
    }));

This will work in .Net 3.5 and above, below that you'll have to be more explicit with the anonymous delegate or just define a named method:

public delegate void myUIDelegate();

myButton.Dispatcher.BeginInvoke(
    DispatcherPriority.Normal,
    new myUIDelegate(EnableButton));

...

private void EnableButton() {
   myButton.Enabled = true;
}
Community
  • 1
  • 1
Mark Pim
  • 9,898
  • 7
  • 40
  • 59
  • No, but see http://stackoverflow.com/questions/303116/system-windows-threading-dispatcher-and-winforms – Mark Pim Sep 14 '10 at 09:57
  • What I meant was: Why a WPF answer? – H H Sep 14 '10 at 10:00
  • Ah :) Mostly because I work in WPF and had assumed the mechanism was common until you asked that question... My mistake. I'll update my answer. – Mark Pim Sep 14 '10 at 10:07
1

For winforms

You need to make use of Control.InvokeRequired property

see below artical

http://www.codeproject.com/KB/cs/AvoidingInvokeRequired.aspx

TalentTuner
  • 17,262
  • 5
  • 38
  • 63