Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WCF: Is it safe to spawn an asynchronous worker thread on the server?

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?

like image 499
Mike Pateras Avatar asked Dec 13 '25 12:12

Mike Pateras


1 Answers

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.

like image 95
Justin Ethier Avatar answered Dec 16 '25 00:12

Justin Ethier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!