Parallel / Concurrent / Async Programming in C# using Tasks
Introduction
This one is a direct result of my work. Recently I was asked to come up with a notification / reminder service to send emails when something remains pending since a week. The initial code looked & worked great locally but once I deployed it to DEV it started running too slow. Obviously, there were 1000's of records on DEV & the service was chocking at the exact code line where I was sending the emails.
Solution
The solution was to use parallel programming techniques. Tasks is what I ended up using. You can follow these steps to add Tasks in your own applications:
Add using System.Threading.Tasks to your code file
Create a Task List to hold each task:
List<Task> sendEmailTaskList = new List<Task>();
Add the Task to this Task List:
sendEmailTaskList.Add(Task.Factory.StartNew(() => { Email.Send( /*some params*/ ); }));
Wait for all tasks to complete:
Task.WaitAll(sendEmailTaskList.ToArray());
Conclusion
By re-factoring the older, slow synchronous code to async / parallel code using Tasks, I could easily see much much better performance on DEV - I think it was at least 300% faster, of course this number really would depend on the actual code / work.
See Also
Please see this related code sample which illustrates using async, await keywords.