I have several process that need to run in the background of a Windows Forms application, because they take too much time and I do not want to freeze the user interface until they completely finish, I would like to have an indicator to show the process of each operation, so far I have a form to show the progress of each operation but my operations run synchronously.
So my question is what is the easiest way to run these operation (that access the database) async??
I forgot one important feature that the application requires, the user will have the option to cancel any operation at any time. I think this requirement complicates the application a lot, at least with my current skills, so basically I would like to enphatize that I need a solution easy to understand, and easy to implement. i am aware there will be good practices to follow but at this point I would like some code working later I with more time I would refactor the code
.NET 4 added the Task Parallel Library, which provides a very clean mechanism for making synchronous operations asynchronous.
It allows you to wrap the sync operation into a Task, which you can then either wait on, or use with a continuation (some code that executes when the task completes).
This will often look something like:
Task processTask = Task.Factory.StartNew(() => YourProcess(foo, bar));
Once you have the task, you have quite a few options, including blocking:
// Do other work, then:
processTask.Wait(); // This blocks until the task is completed
Or, if you want a continuation (code to run when it's complete):
processTask.ContinueWith( t => ProcessCompletionMethod());
You can also use this to combine multiple asynchronous operations, and complete when any or all of them are finished, etc.
Note that using Task or Task<T> in this way has another huge advantage - if you later migrate to .NET 4.5, your API will work as-is, with no code changes, with the new async/await language features coming in C# 5.
I forgot one important feature that the application requires, the user will have the option to cancel any operation at any time.
The TPL was also designed, from it's inception, to work nicely in conjunction with the new cooperative cancellation model for .NET 4. This allows you to have a CancellationTokenSource which can be used to cancel any or all of your tasks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With