[英]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.