I would like to discuss the threading "things" in .NET with you. While other Languages/Frameworks offer a limited clearly defined why how to handle asynchronous calling, there are countless ways to do this in .NET. What I intend to do here, is try to define a kind of "best practice for a given case". In other words: when do you use which treading approach?
Lets start with an enumeration of ways how we can get our code running async:
- Thread (new Thread)
- ThreadPool (ThreadPool.QueueUserWorkItem)
- BackgroundWorker (BackgroundWorker.RunWorkerAsync)
- Delegate (Delegate.BeginInvoke)
- Task Parallels Library
- Parallel Class (Parallel.ForEach)
[Did I forgot any?]
Here is how I decide what type to use:
Thread - usually when i need full control on the thread, e.g. main thread of a sevice.
ThreadPool - short tasks that do not have a high priority - lets say we have an IPC connected to a UI and I just need to losen those calls not to block the UI
BackgroundWorker - UI projects -> Loading/Splash screen
Delegate - usaually only if I need to synchronize with my UI Thread (Dispatcher/Form .Invoke)
Task Parallels Library - not used yet, I guess its a great replacement for "the delegate way" for synchronizing the UI
Parallel - If i need to execute some code for multiple objects - e.g. having a collection of mails from different servers and I need to do something with each of them.
Now its on you, how do you decide what to use when?
If this discussion is going well, i would like to add the Semaphore topic aswell.