C#: background task in a WinForm application containing a long running task

Recently I had to develop a WinForm application doing some checks. During development, with test data, everything was fast and the UI was acceptable. But once running the application with real data, as it was much more, I understood I was facing a long running task, as the UI was not responsive for 2+ hours.

From my studies, I knew the solution was to use the BackgroundWorker component, and one example was in How to: Run an Operation in the Background.

This was fine in the "old" versions of .NET, and even if still supported, I did some researches to see if a more modern approach was available, for example using the Task class introduced in .NET 4.
In fact the solution is pretty easy: you can run your background task with:

Task t = Task.Factory.StartNew(() =>
{
// do your long-time processing here
});
t.ContinueWith((Success) =>
{
// callback when task is complete
}, TaskContinuationOptions.NotOnFaulted);
t.ContinueWith((Fail) =>
{
// callback when task throws an exception
}, TaskContinuationOptions.OnlyOnFaulted);

And in how run now operations in the Task synced with the main thread, necessary to update the UI?
Using the Invoke method, better if after checking with the InvokeRequired property, as shown in C# - ThreadPool and Windows Forms.

Add comment

Loading