Pin-Lui
Pin-Lui

Reputation: 3

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

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

Upvotes: 0

Views: 898

Answers (1)

WBuck
WBuck

Reputation: 5503

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.

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

Upvotes: 3

Related Questions