在BeginInvoke
方法中,调用了私有的LegacyBeginInvokeImpl
方法,它本身又调用了私有方法InvokeAsyncImpl
(InvokeAsync
使用的方法)。因此,它们基本上是一样的。这似乎是一个简单的重构,然而奇怪的是BeginInvoke
方法没有被标记为过时。
BeginInvoke:
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;
}
InvokeAsync :
调用异步方法:
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;
}
BeginInvoke
在未处理的异常时会导致应用程序崩溃,而InvokeAsync
则通过返回的可等待对象将异常传递回来,这是一个巨大的区别。 - jam40jeff