我注意到在.NET 4.5中,WPF Dispatcher获得了一组新的方法,用于在名为InvokeAsync的调度程序线程上执行内容。在.NET 4.5之前,我们有Invoke和BeginInvoke,它们分别以同步和异步方式处理这个问题。
除了命名和可用的略微不同的重载之外,BeginInvoke
和InvokeAsync
方法之间是否有任何主要的区别?
哦,我已经检查过了,这两个都可以用await
编辑:
private async Task RunStuffOnUiThread(Action action)
{
// both of these works fine
await dispatcher.BeginInvoke(action);
await dispatcher.InvokeAsync(action);
}
发布于 2018-03-28 15:06:20
异常处理是不同的。
您可能需要检查以下内容:
private async void OnClick(object sender, RoutedEventArgs e)
{
Dispatcher.UnhandledException += OnUnhandledException;
try
{
await Dispatcher.BeginInvoke((Action)(Throw));
}
catch
{
// The exception is not handled here but in the unhandled exception handler.
MessageBox.Show("Catched BeginInvoke.");
}
try
{
await Dispatcher.InvokeAsync((Action)Throw);
}
catch
{
MessageBox.Show("Catched InvokeAsync.");
}
}
private void OnUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
MessageBox.Show("Catched UnhandledException");
}
private void Throw()
{
throw new Exception();
}
发布于 2013-05-16 01:17:08
方法签名有一个区别:
BeginInvoke(Delegate, Object[])
InvokeAsync(Action)
对于BeginInvoke()
编译器隐式创建数组Object[]
,而对于InvokeAsync()
则不需要这样的数组:
IL_0001: ldarg.0
IL_0002: call instance class [WindowsBase]System.Windows.Threading.Dispatcher [WindowsBase]System.Windows.Threading.DispatcherObject::get_Dispatcher()
IL_0007: ldarg.1
IL_0008: ldc.i4.0
IL_0009: newarr [mscorlib]System.Object
IL_000e: callvirt instance class [WindowsBase]System.Windows.Threading.DispatcherOperation [WindowsBase]System.Windows.Threading.Dispatcher::BeginInvoke(class [mscorlib]System.Delegate, object[])
IL_0014: ldarg.0
IL_0015: call instance class [WindowsBase]System.Windows.Threading.Dispatcher [WindowsBase]System.Windows.Threading.DispatcherObject::get_Dispatcher()
IL_001a: ldarg.1
IL_001b: callvirt instance class [WindowsBase]System.Windows.Threading.DispatcherOperation [WindowsBase]System.Windows.Threading.Dispatcher::InvokeAsync(class [mscorlib]System.Action)
发布于 2019-01-03 22:57:25
嗯,我注意到的一个区别是InvokeAsync有一个泛型重载,它返回一个DispatcherOperation作为返回值,并接受一个Func作为它的委托输入参数。因此,您可以通过InvokeAsync以一种类型安全的方式检索操作的结果,类似于等待任务的结果。
https://stackoverflow.com/questions/13412670
复制相似问题