Multithreaded service, BackgroundWorker vs ThreadPool?

后端 未结 5 1370
暖寄归人
暖寄归人 2020-12-07 19:01

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

5条回答
  •  时光说笑
    2020-12-07 19:51

    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 Threads 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).

提交回复
热议问题