HttpClient.GetByteArrayAsync(…) 在从 UWP 调用的 .NET 标准库中没有互联网连接时出现“死锁”

HttpClient.GetByteArrayAsync(…) “deadlock” when there is no internet connection in .NET standar library calling from UWP

我正在为文档管理系统开发 UWP 应用程序。我正在尝试从我的应用程序中打开文档。当我点击打开文档时,它会下载文档,然后在默认应用程序中打开。但问题是如果互联网在过程中断开连接,则不会下载文档。这意味着已经调用了 httpClinet。我的代码如下

   public async Task<DownloadFileDetail> DownloadFileAsync(int dmsFileId)
    {
        if (dmsFileId <= 0)
        {
            throw new ArgumentException("Invalid DMS File Id");
        }
        try
        {
            return await Task.Run(async () =>
              {
                  DownloadFileDetail fileDetail = new DownloadFileDetail()
                  {
                      DocId = dmsFileId
                  };
                  string apiUrl = $"files/download/latest/{dmsFileId}";
                  HttpClient httpClient = new HttpClient();
                  httpClient.BaseAddress = new Uri(BaseApiUrl);
                  httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {SessionStore.Instance.AuthToken}");
                  var response = await httpClient.GetByteArrayAsync(apiUrl); --> gone deadlock
                  fileDetail.Content = response;
                  return fileDetail;
              });
        }
        catch (Exception ex)
        {

        }
        return new DownloadFileDetail()
        {
            DocId = dmsFileId
        };
    }

下载过程称为 UWP->.NET Standard Libary(包含以上代码)。如果有人帮我解决问题就好了。

谢谢 ss

更新: 上面的代码在我的笔记本电脑上运行,在开发环境中不适用于任何其他笔记本电脑

首先,删除 Task.Run(async () => ...) 调用:

try
{
  DownloadFileDetail fileDetail = new DownloadFileDetail()
  {
      DocId = dmsFileId
  };
  string apiUrl = $"files/download/latest/{dmsFileId}";
  HttpClient httpClient = new HttpClient();
  httpClient.BaseAddress = new Uri(BaseApiUrl);
  httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {SessionStore.Instance.AuthToken}");
  var response = await httpClient.GetByteArrayAsync(apiUrl); --> gone deadlock
  fileDetail.Content = response;
  
  return fileDetail;
}

when there is no internet connection in .NET standar library calling from UWP

如果死锁只发生在没有网络连接的环境下,您可以在发送http请求之前检查网络是否可用。请检查此 NetworkHelper.

if (NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable)
{
// sending the request.
}