Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrying asynchronous file upload on error

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;
    }
}
like image 518
Marius Avatar asked Oct 21 '22 18:10

Marius


1 Answers

Seems like your file stream gets disposed/closed. You need to retry from the very beginning (content = new MultipartFormDataContent(); etc).

like image 120
the_joric Avatar answered Oct 24 '22 09:10

the_joric