3

I have a WCF service method that I want to perform some action asynchronously (so that there's little extra delay in returning to the caller). Is it safe to spawn a System.ComponentModel.BackgroundWorker within the method? I'd actually be using it to call one of the other service methods, so if there were a way to call one of them asynchronously, that would work to.

Is a BackgroundWorker the way to go, or is there a better way or a problem with doing that in a WCF service?

Mike Pateras
  • 14,715
  • 30
  • 97
  • 137

1 Answers1

5

BackgroundWorker is really more for use within a UI. On the server you should look into using a ThreadPool instead.

when-to-use-thread-pool-in-c has a good write-up on when to use thread pools. Essentially, when handling requests on a server it is generally better to use a thread pool for many reasons. For example, over time you will not incur the extra overhead of creating new threads, and the pool places a limit on the total number of active threads at any given time, which helps conserve system resources while under load.

Generally BackgroundWorker is discussed when a background task needs to be performed by a GUI application. For example, the MSDN page for System.ComponentModel.BackgroundWorker specifically refers to a UI use case:

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running. When you want a responsive UI and you are faced with long delays associated with such operations, the BackgroundWorker class provides a convenient solution.

That is not to say that it could not be used server-side, but the intent of the class is for use within a UI.

Community
  • 1
  • 1
Justin Ethier
  • 131,333
  • 52
  • 229
  • 284