Retry to download async file on error

I am trying to upload files to a WPF application. Everything works fine if the server responds, but the application will be used in an environment with an "insecure" Internet connection. So I want to retry the download after a short break if the first attempt fails.

I tried several things with async / await and got the following code. If the server is running, that's fine, but unless the program crashes 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;
    }
}

      

+3


source to share


3 answers


After moving content creation to 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;
    }
}

      

0


source


I think the problem might be what is content

out of scope? Try to create content

inside a method UploadTask

. Also, it might be worth returning Task<bool>

from UploadTask

, and caching is a class level variable (so you don't need to return void).

For example:



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


source


It seems like your file stream has been deleted / closed. You need to try again from the beginning ( content = new MultipartFormDataContent();

etc.).

+1


source







All Articles