If you are using .Net 4.5, you can use await
and async
rather than BackgroundWorker
.
You would create an async
method that returns a Task, and inside that method use Task.Run()
to start the background work.
Here's an example. You'd do all the slow work in the lambda passed to Task.Run()
where I've commented "Do all your slow work here":
private async void btnProcess_Click(object sender, EventArgs e)
{
lblStatus.Text = "Please wait...";
await doSomeWorkAsynchronously();
lblStatus.Text = "Work completed";
}
private async Task doSomeWorkAsynchronously()
{
await Task.Run(()=>
{
// Do all your slow work here.
Thread.Sleep(5000); // Simulate slow work.
});
}
I think this is a bit easier than using BackgroundWorker
.
Note that if all your "slow" methods were already async
(e.g. if you are using asynchronous file I/O) then you might just be able to await
each of your async operations rather than having to create your own task via Task.Run()
.
You can also return a value from the background task. Suppose you wanted to return a string with which to update the label when the background task had completed. You could do that as follows:
private async void btnProcess_Click(object sender, EventArgs e)
{
lblStatus.Text = "Please wait...";
lblStatus.Text = await doSomeWorkAsynchronously();
}
private async Task<string> doSomeWorkAsynchronously()
{
return await Task.Run(()=>
{
// Do all your slow work here.
Thread.Sleep(5000); // Simulate slow work.
return "The task completed.";
});
}