如果行等待任务中有异常,我想测试扩展方法TimeoutAfter中的try / catch块是否捕获到异常。
但是出了点问题,因为try / catch块无法捕获该异常,并且我的应用程序在此行中因该异常而崩溃:
UIApplication.Main(args, null, "AppDelegate");
System.NullReferenceException已引发 你调用的对象是空的
我在等待行之后立即得到System.NullReferenceException;被执行了。我的try / catch块有什么问题?
namespace LeaderboardTest
{
[Register("AppDelegate")]
class Program : UIApplicationDelegate
{
private static Game1 game;
internal static void RunGame()
{
game = new Game1();
game.Run();
}
static void Main(string[] args)
{
UIApplication.Main(args, null, "AppDelegate");
}
public override void FinishedLaunching(UIApplication app)
{
global::Xamarin.Forms.Forms.Init();
RunGame();
}
}
}
我这样称呼扩展方法TimeoutAfter:
bool playertask = false;
playertask = await Extensionmethods.TimeoutAfter(UpdatePlayerCountryData("Germany", "Berlin"), new TimeSpan(0, 0, 0, 5, 0));
private async Task UpdatePlayerCountryData(string country, string city)
{
var resultprofile = await PlayFabClientAPI.UpdateUserDataAsync(new PlayFab.ClientModels.UpdateUserDataRequest()
{
Data = new Dictionary<string, string>() {
{"Country", country},
{"City", city}
},
Permission = PlayFab.ClientModels.UserDataPermission.Public
});
if (resultprofile.Error != null)
Console.WriteLine(resultprofile.Error.GenerateErrorReport());
else
{
Console.WriteLine("Successfully updated user data");
throw new Exception("Test Exception"); // my test exception
}
}
我要捕获异常的扩展方法TimeoutAfter:
namespace LeaderboardTest
{
public static class Extensionmethods
{
public static async Task<bool> TimeoutAfter(this Task task, TimeSpan timeout)
{
using (var timeoutCancellationTokenSource = new CancellationTokenSource())
{
var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
if (completedTask == task)
{
timeoutCancellationTokenSource.Cancel();
try
{
await task;
return true;
}
catch (Exception ex)
{
var message = "Task Exception Message: " + ex.Message;
var innermessage = "Task Inner Exception Message: " + ex.InnerException.Message;
return false;
}
}
else
{
var messagetimeout = "The operation has timed out.";
return false;
}
}
}
}
}