简体   繁体   中英

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

从另一个线程更新某些控件时如何确保线程安全?有人可以帮忙吗?

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;
}

For winforms

You need to make use of Control.InvokeRequired property

see below artical

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM