简体   繁体   中英

WPF “DoEvents”: how to implement it?

I found this two implementation for "DoEvents" method:

SOLUTION 1:

System.Windows.Application.Current.Dispatcher.Invoke(
       System.Windows.Threading.DispatcherPriority.Background,
       new System.Threading.ThreadStart(() => { }));

SOLUTION 2:

System.Windows.Application.Current.Dispatcher.Invoke(
       System.Windows.Threading.DispatcherPriority.Background,
       new System.Action(delegate { }));

Could you explain what is the difference between these two implementations, and what is the most appropriate to use?

Thanks.

They both are delegates,when your event execution needs to done it will initiate the events when your criteria met (eg, Here in case when execution reached and dispatcher priority background reached) They are just two different implementation ways you can refer

What is the difference between Delegate & Action in C#

or msdn for information

http://msdn.microsoft.com/en-us/library/system.threading.threadstart(v=vs.110).aspx

http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx

There is no difference between both solutions except the syntax. ThreadStart and Action are both delegates which have the same declaration and only a name is different:

public delegate void ThreadStart();
public delegate void Action();

You can also create your own delegate and use is in the same way eg:

public delegate void MyOwnAction();
...
Application.Current.Dispatcher.Invoke(
    DispatcherPriority.Background, new MyOwnAction(() => { }));

You can also use a specific method and not anonymous one:

private void Target()
{
    ...
}

Application.Current.Dispatcher.Invoke(
    DispatcherPriority.Background, new MyOwnAction(Target));

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