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

标签 c# xamarin.ios xamarin async-await

我在 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/

相关文章:

.net - 在 Xamarin iOS 中使用 .NET 标准

c# - 避免 Xamarin Camera 的 OK Retry 按钮

android - 是否可以从 Linux CLI 编译 Xamarin for Android?

Xamarin 表单 : How to take picture?

c# - 在存储库中 try catch

c# - C#中如何等待点击

c# - 在 MonoTouch.Dialog 中设置按钮颜色

c# - 我应该为图像和颜色使用公共(public)静态字段吗?

c# - 方法以随机顺序调用 (C#)

c# - 为什么具有默认值枚举参数的泛型类的构造函数无法调用该类的 protected 方法?