Xamarin:任务引发的异常不会传播
本文关键字:异常 传播 任务 Xamarin | 更新日期: 2023-09-27 18:21:03
我在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能像在微软的async/await实现中一样工作。我是不是错过了什么?
您不能将await
作为constructor
内部的方法,因此无法捕获Exception
。
要捕获Exception
,必须执行await
操作。
这里有两种从构造函数调用异步方法的方法:
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());
}
});