繁体   English   中英

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

[英]Xamarin: Exceptions raised from tasks are not propagated

我在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能像微软的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());
    }    
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM