重试异步文件上传的错误 [英] Retrying asynchronous file upload on error

查看:97
本文介绍了重试异步文件上传的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要上传的文件在WPF应用程序。一切工作正常,如果服务器响应,但应用程序将与不安全的网络连接的环境中使用。所以,我想休息片刻后重试上传,如果第一次尝试失败了。

我试了好东西异步/等待并结束了与以下code。 如果服务器运行的是一切都很好,但如果没有该计划将失败,并在while循环的第二次迭代一个的ObjectDisposedException。

任何想法?

 私人无效UploadButton_Click(对象发件人,RoutedEventArgs E)
{
    //构建内容发送
    内容=新MultipartFormDataContent();
    VAR FILESTREAM =新的FileStream(文件路径,FileMode.Open);
    VAR文件名= System.IO.Path.GetFileName(文件路径);
    content.Add(新StreamContent(文件流),文件,文件名);
    content.Add(新的StringContent(terminal_id.ToString()),terminal_id);

    UploadTask(内容);
    / * VAR task_a =新任务(()=> UploadTask(内容));
    task_a.Start(); * /
}

私人异步无效UploadTask(HttpContent内容)
{
    布尔成功= FALSE;
    INT计数器= 0;

    而(计数器3;&安培;&安培;!成功)
    {
        的Debug.WriteLine(开始上传);
        成功=等待UploadFileAsync(内容);
        的Debug.WriteLine(完成上传的结果。+ success.ToString());
        (!成功)//如果System.Threading.Thread.Sleep(5000);
        反++;
    }
}

私人异步任务<布尔> UploadFileAsync(HttpContent内容)
{
    VAR消息=新的Htt prequestMessage();
    message.Method = HttpMethod.Post;
    message.Content =内容;
    message.RequestUri =新的URI(target_url);

    使用(HttpClient的客户端=新的HttpClient())
    {
        尝试
        {
            HTT presponseMessage解析度=等待client.SendAsync(消息);
            如果(res.IsSuccessStatus code)返回true;
        }
        赶上(Htt的prequestException HRE)
        {
            的Debug.WriteLine(hre.ToString());
        }
        返回false;
    }
}
 

解决方案

移动创造的内容为UploadFileAsync()它的工作原理之后。结果:

 任务<布尔>新任务;

私人无效UploadButton_Click(对象发件人,RoutedEventArgs E)
{
    newTask = UploadTask();
}

私人异步任务<布尔> UploadTask()
{
    布尔成功= FALSE;
    INT计数器= 0;

    而(计数器3;&安培;&安培;!成功)
    {
        的Debug.WriteLine(开始上传);
        成功=等待UploadFileAsync();
        的Debug.WriteLine(完成上传的结果。+ success.ToString());
        如果(!成功)System.Threading.Thread.Sleep(5000);
        反++;
    }
    返回成功;
}

私人异步任务<布尔> UploadFileAsync()
{
    MultipartFormDataContent内容=新MultipartFormDataContent();
    VAR FILESTREAM =新的FileStream(文件路径,FileMode.Open);
    VAR文件名= System.IO.Path.GetFileName(文件路径);
    content.Add(新StreamContent(文件流),文件,文件名);
    content.Add(新的StringContent(terminal_id.ToString()),terminal_id);

    VAR消息=新的Htt prequestMessage();
    message.Method = HttpMethod.Post;
    message.Content =内容;
    message.RequestUri =新的URI(target_url);

    使用(HttpClient的客户端=新的HttpClient())
    {
        尝试
        {
            HTT presponseMessage解析度=等待client.SendAsync(消息);
            如果(res.IsSuccessStatus code)返回true;
        }
        赶上(Htt的prequestException HRE)
        {
            的Debug.WriteLine(hre.ToString());
        }
        返回false;
    }
}
 

I'm trying to upload files in a WPF-application. Everything works fine if the server responds but the application will be used in an environment with "unsafe" internet connection. So I want to retry uploading after a short break if the first attempt failed.

I tried several things with async/await and ended up with the following code. If the server is running everything is fine, but if not the program fails with an ObjectDisposedException in the second iteration of the while-loop.

Any ideas?

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

解决方案

After moving the creation of the content into UploadFileAsync() it works. Result:

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

这篇关于重试异步文件上传的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆