错误时重试异步文件上载

时间:2013-01-29 09:20:23

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

我正在尝试在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;
    }
}

3 个答案:

答案 0 :(得分:1)

我认为问题可能是content超出了范围?尝试在content方法中创建UploadTask。此外,可能值得从Task<bool>返回UploadTask并缓存它是类级变量(因此您不必返回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;
}

答案 1 :(得分:1)

好像你的文件流被处理/关闭了。您需要从一开始就重试(content = new MultipartFormDataContent();等)。

答案 2 :(得分:0)

将内容创建移动到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;
    }
}
相关问题