gpt4 book ai didi

c# - Xamarin:不传播任务引发的异常

转载 作者:可可西里 更新时间:2023-11-01 08:11:16 25 4
gpt4 key购买 nike

我在 Xamarin 中有以下代码(在 ios 中测试):

private static async Task<string> TaskWithException()
{
return await Task.Factory.StartNew (() => {
throw new Exception ("Booo!");
return "";
});
}

public static async Task<string> RunTask()
{
try
{
return await TaskWithException ();
}
catch(Exception ex)
{
Console.WriteLine (ex.ToString());
throw;
}
}

调用它作为 await RunTask(),确实会从 TaskWithException 方法中抛出异常,但永远不会命中 RunTask 中的 catch 方法.这是为什么?我希望 catch 能够像 Microsoft 的 async/await 实现一样工作。我错过了什么吗?

最佳答案

您不能await constructor 中的方法,所以这就是您无法捕获Exception 的原因。

要捕获异常,您必须等待操作。

这里有两种从构造函数调用异步方法的方法:

1. ContinueWith 解决方案

RunTask().ContinueWith((result) =>
{
if (result.IsFaulted)
{
var exp = result.Exception;
}
});

2. Xamarin 表单

Device.BeginInvokeOnMainThread(async () =>
{
try
{
await RunTask();
}
catch (Exception ex)
{
Console.WriteLine (ex.ToString());
}
});

3.iOS

InvokeOnMainThread(async () =>
{
try
{
await RunTask();
}
catch (Exception ex)
{
Console.WriteLine (ex.ToString());
}
});

关于c# - Xamarin:不传播任务引发的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25730018/

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