Ryan
Ryan

Reputation: 257

C# Wait for async operation to finish

I'm wondering what the best approach might be for what I'm trying to do. My application has a button that starts a background download operation, and then performs some actions dependent on the downloaded files.

It's like a "The game will begin shortly once necessary data is downloaded" situation, where the user may still use the main form.

private void btnStart_Click(object sender, EventArgs e)
{
    //execute some code

    Downloader.RunWorkerAsync(files); //this worker reports progress to the main form

    while (Downloader.IsBusy)
        Application.DoEvents();

    //execute some more code
}

I'm aware that doing it that way is not good at all.

I cannot execute the download code synchronously, because the main form needs to remain responsive during the download operation. I also cannot put the final code into the download completed event, as it is used by many other areas of the program and must remain a "generic" download system.

So, is there a way to do what I want? I do not have any experience with other async methods.

Upvotes: 2

Views: 839

Answers (2)

daryal
daryal

Reputation: 14929

I think you should use asynchronous programming features of the .net 4.5 framework (await and async).

refer to async programming

Upvotes: 1

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33391

If you use BackgrounWorker you must configure it properly. BW has RunWorkerCompleted event to which you must subscribe to handle completion of you async work.

Upvotes: 2

Related Questions