WPF Dispatcher 的 InvokeAsync 和 BeginInvoke 有什么区别 [英] What's the difference between InvokeAsync and BeginInvoke for WPF Dispatcher
问题描述
我注意到在 .NET 4.5 中 WPF Dispatcher一组新的方法,用于在 Dispatcher 的线程上执行名为 InvokeAsync 的内容.在 .NET 4.5 之前,我们有 调用 和 BeginInvoke 分别同步和异步处理.
I noticed in .NET 4.5 that the WPF Dispatcher had gotten a new set of methods to execute stuff on the Dispatcher's thread called InvokeAsync. Before, .NET 4.5 we had Invoke and BeginInvoke which handled this syncronously and asynchronously respectively.
除了命名和可用的重载略有不同之外,BeginInvoke
和 InvokeAsync
方法之间有什么主要区别吗?
Besides the naming and the slightly different overloads available, are there any major differences between the BeginInvoke
and the InvokeAsync
methods?
哦,我已经检查过了,两者都可以await
ed:
Oh, and I already checked, both can be await
ed:
private async Task RunStuffOnUiThread(Action action)
{
// both of these works fine
await dispatcher.BeginInvoke(action);
await dispatcher.InvokeAsync(action);
}
推荐答案
没有区别,因为 BeginInvoke
方法调用私有的 LegacyBeginInvokeImpl
方法,而它的lef 调用私有方法InvokeAsyncImpl
(InvokeAsync
使用的方法).所以它基本上是一样的.看起来这是一个简单的重构,但奇怪的是 BeginInvoke
方法没有被标记为过时.
There are no differences as the BeginInvoke
method calls a private LegacyBeginInvokeImpl
method which itslef calls the private method InvokeAsyncImpl
(the method used by InvokeAsync
). So it's basically the same thing. It seems like it's a simple refactoring, however it's strange the BeginInvoke
methods weren't flagged as obsolete.
开始调用:
public DispatcherOperation BeginInvoke(DispatcherPriority priority, Delegate method)
{
return this.LegacyBeginInvokeImpl(priority, method, null, 0);
}
private DispatcherOperation LegacyBeginInvokeImpl(DispatcherPriority priority, Delegate method, object args, int numArgs)
{
Dispatcher.ValidatePriority(priority, "priority");
if (method == null)
{
throw new ArgumentNullException("method");
}
DispatcherOperation dispatcherOperation = new DispatcherOperation(this, method, priority, args, numArgs);
this.InvokeAsyncImpl(dispatcherOperation, CancellationToken.None);
return dispatcherOperation;
}
调用异步:
public DispatcherOperation InvokeAsync(Action callback, DispatcherPriority priority)
{
return this.InvokeAsync(callback, priority, CancellationToken.None);
}
public DispatcherOperation InvokeAsync(Action callback, DispatcherPriority priority, CancellationToken cancellationToken)
{
if (callback == null)
{
throw new ArgumentNullException("callback");
}
Dispatcher.ValidatePriority(priority, "priority");
DispatcherOperation dispatcherOperation = new DispatcherOperation(this, priority, callback);
this.InvokeAsyncImpl(dispatcherOperation, cancellationToken);
return dispatcherOperation;
}
这篇关于WPF Dispatcher 的 InvokeAsync 和 BeginInvoke 有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!