Search code examples
c#uwpdotnet-httpclient.net-standard

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


I am developing a UWP application for a document management system. I am trying to open documents from my application. When I click the open document, It is going to download the document and then open in the default application. But the problem is document is not downloaded if the internet is a disconnect in the middle of the process. It means when httpClient is already called. My code is as following

   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
        };
    }

Download process called as UWP->.NET Standard Library (holds above code). It will be great if someone helps me to solve the problem.

Thanks ss

Update: The above code is working on my laptop and not working on any other laptop in dev environment


Solution

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

    If the deadlock only occurs in no internet connection environment, you could check if internet is available before sending http request. Please check this NetworkHelper.

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