I have a .NET 3.5 Windows Service. I\'m testing with a small application that just sleeps threads after starting them, for random timespans of 300 to 6500ms. I have various
I wrote up a fairly exhaustive overview of various implementations of asynchronous background tasks on my blog. The summary is: prefer Task
; the second choice would be BackgroundWorker
; and only use Thread
or ThreadPool.QueueUserWorkItem
if you really need to.
Reasons: it's easier to detect and recover from errors, and it's easier to synchronize back to a UI.
To answer your specific questions:
BackgroundWorker
works in any host, including WinForms and WPF (and even ASP.NET!), because it is based on SynchronizationContext. Windows services do not have a SynchronizationContext
, but you can use ActionThread
from the Nito.Async library, which comes with a SynchronizationContext
.
If I read your question correctly, you currently have Thread
s and are considering ThreadPool
and BackgroundWorker
. Of those choices, I recommend BackgroundWorker
, but if you have the chance, use the new Task
class in .NET 4.0 (if you install Microsoft Rx, you can also use Task
in .NET 3.5).