【发布时间】:2015-04-26 19:27:02
【问题描述】:
我有验证服务。 catch (AccountNotFoundException) 不会捕获异常,除非我在 Task.Run 中调用它。奇怪的是,测试用例很好。为什么?是因为 task.start() 与 catch 处于不同的级别吗?
public override string GetUserNameByEmail(string email)
{
var task = client.GetUserByEmail(email, false);
return task.Result;
// I changed to
// return Task.Run(() => client.GetUserByEmail(email, false)).Result.UserName;
// and I was able to catch the exception
}
public async Task<AccountDetails> GetAccountDetailsByEmail(string email)
{
try
{
return await Call(() => client.getAccountDetailsByEmail(email));
}
catch (AccountNotFoundException)
{
return null;
}
}
private async Task<T> Call<T>(Func<T> call)
{
try
{
transport.Open();
var thriftTask = new Task<T>(call);
thriftTask.Start();
return await thriftTask;
}
catch (DatabaseException e)
{
Logger.Error(e);
throw;
}
finally
{
transport.Close();
}
}
测试用例运行良好
[TestMethod]
public async Task Nonexisting_User_I_Expect_To_Be_Null()
{
var user = Provider.GetUser("idontexist@bar.com", false);
Assert.IsNull(user);
}
编辑:
我有以下理论为什么我的代码运行正常:代码运行正常是因为我很幸运。请求和异步由同一个线程处理,因此它共享相同的上下文,因此不会阻塞。
【问题讨论】:
标签: c# .net exception asynchronous asp.net-membership