Search code examples
c#asp.netthreadpool

ThreadPool.QueueUserWorkItem Only Utilizing 1 of 3 Cores


I have lengthy call to a web service within an ASP.NET application that is being called through ThreadPool.QueueUserWorkItem. The call takes around 2 minutes to complete and sends about 2000 records to an external data store. Everything seems to be running smoothly, except I have noticed that when these calls are made in the production environment running IIS7, only 1 CPU core is being utilized, and it is maxed out. How can I get this to balance the workload across all available CPU cores?


Solution

  • Assuming you are using .Net 4.0+

    If you have 2000 records and need to make 2000 related calls to a service of some sort, you can use this approach:

    List<RecordType> records = GetMyRecords();
    Parallel.ForEach(records, record => {
        MakeMyServiceCall(record);
    });
    

    This will run the MakeMyServiceCall method for each indivdual record in parallel; the parallel library uses the ThreadPool threads behind the scenes which will transparently distribute the load over the available cores.