November 8, 2008

.NET Thread Pool Extension

Recently I have finished one of the most exciting component designs over the past couple of months. The customer wanted to have an extention to the .NET ThreadPool class, which would provide him with the control over individual worker threads. Although by default ThreadPool does not provide access to the individual background threads which it use, Stephen Toub wrote a couple of articles at MSDN magazine with an explanation how to do that (as an example you may take a look at the article here )

The other requirement of the design was to select jobs for execution based on priority and to change the priority of the jobs in the runtime. For the former task we could use the Priority Queue implementation. The latter task was challanging since that Priority Queue implementation had only two methods - Enqueue and Dequeue. So there was no possibility to look through the Queue to change the priority of the item. To solve this problem I used the following strategy:
  1. A wrapper class was provided for the job, which was identified by a unique ID
  2. The user could use the ID of the job to indicate that the priority for this job should be changed
  3. The Thread Pool class used an internal job ID and a mapping from the user's ID to the internal one
  4. The Priority Queue contained the internal job IDs
  5. When the user wanted to change the priority of the job the following iterations took place:

    • New internal ID for the job was created and sent to the Priority Queue
    • Mapping from the user's ID to the internal one was updated
    • The system remembered that the old internal ID is not valid any more and should not be processed when it will be
      dequeued


http://www.linkedin.com/in/oldbam

No comments: