0

i have problem with download async. Sometime it crashed. The method is in try and catch, but isn't helping.

How can I prevent file download from stopping the entire application?

I have stact trace, but is not helping, i know where the error is, but why the app is crasched ?

Inner exceptions:
An error occurred while sending the request.
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at WhiteListAPI.FileTool.<DownloadAsync>d__0.MoveNext()
— End of stack trace from previous location where exception was thrown —
   at System.Runtime.CompilerServices.AsyncMethodBuilderCore.<>c.<ThrowAsync>b__6_1(Object state)
   at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()
   at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
The underlying connection was closed: An unexpected error occurred on a receive.
  at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
   at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
  at System.Net.Security._SslStream.EndRead(IAsyncResult asyncResult)
   at System.Net.TlsStream.EndRead(IAsyncResult asyncResult)
   at System.Net.PooledStream.EndRead(IAsyncResult asyncResult)
   at System.Net.Connection.ReadCallback(IAsyncResult asyncResult)
An existing connection was forcibly closed by the remote host
  at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
   at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
public async void DownloadAsync(string fileAdress, string fileDestination)
    {
      using (var client = new HttpClient())
      {
          client.BaseAddress = new Uri(fileAdress);
          client.Timeout = TimeSpan.FromMinutes(10);
          var request = new HttpRequestMessage(HttpMethod.Post, fileAdress);
          var sendTask = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
          var response = sendTask.EnsureSuccessStatusCode();
          var httpStream = await response.Content.ReadAsStreamAsync();
          using (var fileStream = System.IO.File.Create(fileDestination))
          using (var reader = new StreamReader(httpStream))
          {
            httpStream.CopyTo(fileStream);
            fileStream.Flush();
          }
      }
    }      

    public FileWhiteList Download(string fileAdress, string fileDestination)
    {
      var status = new FileWhiteList();     
      try
      { 
        DownloadAsync(fileAdress, fileDestination);
      }
      catch (Exception ex)
      {
        status.report = ex.ToString();
        status.ok = false;
      }
      if (!string.IsNullOrEmpty(status.report))
        throw new Exception(status.report);

      status.report = "The file has been downloaded correctly " + fileAdress;
      status.ok = true;
      return status;
    }
  • 1
    Does this answer your question? [Catch an exception thrown by an async void method](https://stackoverflow.com/questions/5383310/catch-an-exception-thrown-by-an-async-void-method). In short, you need to `await` your download *somewhere* and the exception will bubble up to where you await it so you can handle it – MindSwipe Aug 04 '20 at 06:16
  • 1
    Don't forget to use “Async All the Way Down” https://stackoverflow.com/questions/41438736/async-all-the-way-down-well-whats-all-the-way-at-the-bottom – Salah Akbari Aug 04 '20 at 06:21
  • i try use this solution, cannot use them – Łukasz Dziądziak Aug 04 '20 at 06:30
  • To be explicit, you probably should not use `async void` here, `async Task` should be supported. If you can't, then you're out of luck, because that's precisely the issue – Pac0 Aug 04 '20 at 06:30
  • 1
    You can read [here](https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void) why you should avoid `async void`. – Theodor Zoulias Aug 04 '20 at 06:35
  • `i try use this solution, cannot use them` Why not? – mjwills Aug 04 '20 at 06:55

0 Answers0