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实现一样工作.我错过了什么吗?
你不能在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)
归档时间: |
|
查看次数: |
2088 次 |
最近记录: |