【发布时间】:2020-08-23 10:34:45
【问题描述】:
我在 xamarin 中开发我的移动应用程序并发送 x 个请求以显示我的应用程序的主页。
我的代码如下:
var taskcoll = _mainArticlesAppService.GetWelcomeStartColl().ContinueWith(async (res) =>
{
_applicationContext.Categories = res.Result.Categories;
});
var taskheros = _mainArticlesAppService.GetWelcomeHerosProfileDto().ContinueWith((res) =>
{
_applicationContext.HerosProfileDto = res.Result;
RaisePropertyChanged(() => HerosProfileDto);
});
List<Task> tasksInit = new List<Task>();
tasksInit.Add(taskcoll);
tasksInit.Add(taskheros);
await Task.WhenAll(tasksInit).ConfigureAwait(false);
当没有问题时,一切都很好。
但是,当请求无法连接到远程 api 服务器时,它会在我的代码中引发 ecxeption,然后死锁,我无法再做任何事情并且我的屏幕被冻结。
我发生死锁的代码是:
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,
CancellationToken cancellationToken)
{
int count = 0;
using (var cts = new CancellationTokenSource(new TimeSpan(0, 0, 30)))
{
HttpResponseMessage response = null;
try
{
response = await base.SendAsync(request, cts.Token);
}
catch(Exception ex)
{
throw ex; // --> Deadlock
}
if (response.StatusCode == HttpStatusCode.Unauthorized &&
HasBearerAuthorizationHeader(request))
{
return await HandleUnauthorizedResponse(request, response, cancellationToken);
}
return response;
}
}
【问题讨论】:
标签: c# xamarin async-await task deadlock