Home > Blockchain >  Run and Wait for async Task to complete in a Windows Form Application
Run and Wait for async Task to complete in a Windows Form Application

Time:08-27

How can I wait for an async task to complete without freezing the whole Application?

This function works but Cout() gets called while the File is still downloading.

private void Btn_test_Click(object sender, EventArgs e)
{  
    var task = Task.Run(async () => { await DownloadWebFile("https://speed.hetzner.de/100MB.bin", AppDomain.CurrentDomain.BaseDirectory   "//100MB.bin"); });
        
     Cout(DownloadSuccessMsg);    
}

when I do this the whole Application freezes:

private void Btn_test_Click(object sender, EventArgs e)
{  
    var task = Task.Run(async () => { await DownloadWebFile("https://speed.hetzner.de/100MB.bin", AppDomain.CurrentDomain.BaseDirectory   "//100MB.bin"); });
    task.Wait();     
    Cout(DownloadSuccessMsg);    
}

How can I wait correctly before running other code depending on the downloaded file?

private static async Task DownloadWebFile(string url, string fullPath)
{
     using var client = new DownloadManager(url, fullPath);
        client.ProgressChanged  = (totalFileSize, totalBytesDownloaded, progressPercentage) =>
        {
            SetProgressBarValue((int)progressPercentage);
        };

    await client.StartDownload();            
}

CodePudding user response:

You can mark the method as async void. Returning void from an asynchronous method is usually not a great idea, but in the case of an event handler it's usually considered acceptable.

I would wrap this code in a try catch though.

private async void Btn_test_Click(object sender, EventArgs e)
{  
    try
    {
        await DownloadWebFile("https://speed.hetzner.de/100MB.bin", AppDomain.CurrentDomain.BaseDirectory   "//100MB.bin");
        Cout(DownloadSuccessMsg);   
    }
    catch (Exception ex)
    {
        // Alert the user that an error has occurred.
    } 
}
  • Related