[WPF][Update]Use Dispatcher

1. When do we use Dispatcher?

For example, if we create a new thread that will deal some time cost stuff. After the thread finish its work, we want to update the WPF UI. Then, it is time to use Dispatcher.

     Dispatcher.Invoke(new Action(MethodName), null);

If you want to update the UI asynchronizly, we use:

     Dispatcher.BeginInvoke(new Action(MethodName), null);

2. Dispatcher or controlObject.Dispatcher?

The truth is , by default, there is only one Dispatcher in a WPF window. Dispatcher and controlObject.Dispatcher are the same. You can test it by print both of their object hash code out.

    Console.WriteLine(Dispatcher.GetHashCode().ToString());

    Console.WriteLine(testBtn.Dispatcher.GetHashCode().ToString());

3. Lambda style:

  Dispatcher.BeginInvoke(() => { });

 

 

blog comments powered by Disqus