gpt4 book ai didi

c# - WPF Dispatcher 的 InvokeAsync 和 BeginInvoke 有什么区别

转载 作者:IT王子 更新时间:2023-10-29 03:45:46 33 4
gpt4 key购买 nike

我注意到在 .NET 4.5 中 WPF Dispatcher已经获得了一组新方法来在名为 InvokeAsync 的 Dispatcher 线程上执行内容.之前,.NET 4.5 我们有 InvokeBeginInvoke分别以同步和异步方式处理。

除了命名和可用的重载略有不同之外,BeginInvokeInvokeAsync 方法之间是否存在任何重大差异?

哦,我已经检查过了,两者都可以awaited:

private async Task RunStuffOnUiThread(Action action)
{
// both of these works fine
await dispatcher.BeginInvoke(action);
await dispatcher.InvokeAsync(action);
}

最佳答案

异常处理不同。

您可能需要检查以下内容:

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();
}

关于c# - WPF Dispatcher 的 InvokeAsync 和 BeginInvoke 有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13412670/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com