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实现中一样工作。我是不是错过了什么?

Xamarin:任务引发的异常不会传播

您不能将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());
    }    
});