【问题标题】:Retrying asynchronous file upload on error出错时重试异步文件上传
【发布时间】:2013-01-12 19:35:43
【问题描述】:

我正在尝试在 WPF 应用程序中上传文件。如果服务器响应,一切正常,但应用程序将在“不安全”互联网连接的环境中使用。因此,如果第一次尝试失败,我想在短暂休息后重试上传。

我用 async/await 尝试了几件事,最后得到了以下代码。 如果服务器正在运行,一切正常,但如果不是,则程序在 while 循环的第二次迭代中失败并返回 ObjectDisposedException。

有什么想法吗?

private void UploadButton_Click(object sender, RoutedEventArgs e)
{
    // build content to send
    content = new MultipartFormDataContent();
    var filestream = new FileStream(filePath, FileMode.Open);
    var fileName = System.IO.Path.GetFileName(filePath);
    content.Add(new StreamContent(filestream), "file", fileName);
    content.Add(new StringContent(terminal_id.ToString()), "terminal_id");

    UploadTask(content);
    /*var task_a = new Task(() => UploadTask(content));
    task_a.Start();*/
}

private async void UploadTask(HttpContent content)
{
    bool success = false;
    int counter = 0;

    while (counter < 3 && !success)
    {
        Debug.WriteLine("starting upload");
        success = await UploadFileAsync(content);
        Debug.WriteLine("finished upload. result " + success.ToString());
        //if (!success) System.Threading.Thread.Sleep(5000);
        counter++;
    }
}

private async Task<bool> UploadFileAsync(HttpContent content)
{
    var message = new HttpRequestMessage();
    message.Method = HttpMethod.Post;
    message.Content = content;
    message.RequestUri = new Uri(target_url);

    using (HttpClient client = new HttpClient())
    {
        try
        {
            HttpResponseMessage res = await client.SendAsync(message);
            if (res.IsSuccessStatusCode) return true;
        }
        catch (HttpRequestException hre)
        {
            Debug.WriteLine(hre.ToString());
        }
        return false;
    }
}

【问题讨论】:

    标签: c# .net wpf asynchronous async-await


    【解决方案1】:

    我认为问题可能是content 超出范围?尝试在UploadTask 方法中创建content。此外,可能值得从 UploadTask 返回 Task&lt;bool&gt; 并将其缓存为类级别变量(因此您不必返回 void)。

    例如:

    Task<bool> newTask;
    
    private void UploadButton_Click(object sender, RoutedEventArgs e)
    {
        newTask = UploadTask();
    
    }
    
    private async Task<bool> UploadTask()
    {
    bool success = false;
    int counter = 0;
    
    // build content to send
    HttpContent content = new MultipartFormDataContent();
    var filestream = new FileStream(filePath, FileMode.Open);
    var fileName = System.IO.Path.GetFileName(filePath);
    content.Add(new StreamContent(filestream), "file", fileName);
    content.Add(new StringContent(terminal_id.ToString()), "terminal_id");
    
    while (counter < 3 && !success)
    {
        Debug.WriteLine("starting upload");
        success = await UploadFileAsync(content);
        Debug.WriteLine("finished upload. result " + success.ToString());
    
        counter++;
    }
    
    return success;
    }
    

    【讨论】:

    • 恐怕(几乎)没有任何改变。异常在后台任务中引发,但结果保持不变。但是有了这个建议,我将内容的创建移到 UploadFileAsync() 并且它可以工作。谢谢!
    【解决方案2】:

    您的文件流似乎已被处置/关闭。您需要从头开始重试(content = new MultipartFormDataContent(); 等)。

    【讨论】:

      【解决方案3】:

      将内容的创建移到 UploadFileAsync() 之后,它就可以工作了。结果:

      Task<bool> newTask;
      
      private void UploadButton_Click(object sender, RoutedEventArgs e)
      {
          newTask = UploadTask();
      }
      
      private async Task<bool> UploadTask()
      {
          bool success = false;
          int counter = 0;
      
          while (counter < 3 && !success)
          {
              Debug.WriteLine("starting upload");
              success = await UploadFileAsync();
              Debug.WriteLine("finished upload. result " + success.ToString());
              if (!success) System.Threading.Thread.Sleep(5000);
              counter++;
          }
          return success;
      }
      
      private async Task<bool> UploadFileAsync()
      {
          MultipartFormDataContent content = new MultipartFormDataContent();
          var filestream = new FileStream(filePath, FileMode.Open);
          var fileName = System.IO.Path.GetFileName(filePath);
          content.Add(new StreamContent(filestream), "file", fileName);
          content.Add(new StringContent(terminal_id.ToString()), "terminal_id");
      
          var message = new HttpRequestMessage();
          message.Method = HttpMethod.Post;
          message.Content = content;
          message.RequestUri = new Uri(target_url);
      
          using (HttpClient client = new HttpClient())
          {
              try
              {
                  HttpResponseMessage res = await client.SendAsync(message);
                  if (res.IsSuccessStatusCode) return true;
              }
              catch (HttpRequestException hre)
              {
                  Debug.WriteLine(hre.ToString());
              }
              return false;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-03-29
        • 2021-12-25
        • 2018-02-01
        • 1970-01-01
        • 2011-09-17
        • 2014-06-02
        • 2012-08-22
        • 1970-01-01
        相关资源
        最近更新 更多