I have a legacy application that needs to deal with scalability issues. This is a WCF service that listens to requests received from a back end system and does some computations/processing of data based on those requests. The computations are not cpu intensive although in some cases it calls some third party library APIs (which itself calls SOAP based web-services). There aren't any database calls involved. Here is how the service is been set up.
[ServiceContract]
public interface IMyService
{
[OperationContract]
ProcessingResult ProcessData(int dataId, string dataDescription);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple, IncludeExceptionDetailInFaults = true)]
public class MyService : IMyService
{
ProcessingResult ProcessData(int dataId, string dataDescription)
{
// Some data processing using third party library APIs and return ProcessingResult instance.
}
}
public class ProcessingResult
{
public int Code;
public string Message;
}
The issue here is that under load conditions, there are so many calls of ProcessData method that overloads the system. In these scenarios,I have seen hundreds of threads running at a time. They eventually do complete the task but system slows down drastically. In order to deal with it, I am considering to add some sort of gating mechanism. Something like delegating the work to another class that queue the processing data calls to a ThreadPool with threshold on maximum number of requests process simultaneously. The problem I see with this approach is that ProcessData still need to wait for the work queued in threadpool to finish before returning ProcessingResult instance.
Googling seem to suggest that async-await could be a nice pattern, however, I am little restricted as this application isn't using latest and greatest .net versions and it could be a big ask to migrate to newer .NET version at this point. Any suggestions on how can I use ThreadPool.QueueUserWorkItem mechanims in this class with ability to wait on a particular items to finish?