Using the thread pool
There are other ways to use
ThreadPool threads in a .NET application. Let’s discuss a situation where you want to accomplish the same result that was achieved with
await in the previous example, but the methods to fetch the order data are not marked as
async. One option is to update the methods to be
async. If that code is not within your control to change, you have some other options available.
ThreadPool class has a method called
QueueUserWorkItem. This method accepts a method to call and queues it for execution on the thread pool. We could use it with our project like this:
There are a few problems with using this method. The primary issue is that there is no return value to get the list of orders from the method call. You could work around this issue with some wrapper methods that update a shared thread-safe collection such as the
BlockingCollection. That isn’t a great design...