Xamarin:从任务中提取的异常不会传播

mad*_*ode 13 c# xamarin.ios async-await xamarin

我在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

jze*_*ino 7

你不能在await一个方法内constructor,所以这就是为什么你不能抓住Exception.

抓住Exception你必须await的操作.

我有两种方法从构造函数调用异步方法:

1. ContinueWith解决方案

RunTask().ContinueWith((result) =>
{
    if (result.IsFaulted)
    {
        var exp = result.Exception;
    }      
});
Run Code Online (Sandbox Code Playgroud)

2. Xamarin表格

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

3. iOS

InvokeOnMainThread(async () =>
{
    try
    {
        await RunTask();    
    }
    catch (Exception ex)
    {
        Console.WriteLine (ex.ToString());
    }    
});
Run Code Online (Sandbox Code Playgroud)

  • 感谢您抽出宝贵时间回答这个老问题.从我记忆中,我们使用#2来解决当时的问题.对我没有跟进和回答我自己的问题感到羞耻!:( (2认同)