Note that there are some explanatory texts on larger screens.

plurals
  1. POGeneric ThreadPool in .NET
    primarykey
    data
    text
    <p>Here's a relatively common task for me, and, I think, for many a .NET programmer:<br> I want to use the .NET ThreadPool for scheduling worker threads that need to process a given type of tasks.</p> <p>As a refresher, the signatures for the queueing method of the ThreadPool and its associated delegate are:</p> <pre><code>public static bool QueueUserWorkItem ( WaitCallback callBack, Object state ) public delegate void WaitCallback (Object state) </code></pre> <p>Therefore, a typical generic worker thread class would look something like:</p> <pre><code>public class Worker&lt;T&gt; { public void schedule(T i_task) { ThreadPool.QueueUserWorkItem(execute, i_task) } private void execute(Object o){ T task = (T)o; //What happened to the type safety? executeTask(task); } private void executeTask(T i_task){ //process i_task } } </code></pre> <p>Notice the type of the <code>state</code> parameter? It's <em><code>Object</code></em> !</p> <p>What's the compelling reason why the .NET team chose not to make the <code>QueueUserWorkItem</code> method (or the whole <code>ThreadPool</code> class) generic? I can't believe they just overlooked it.</p> <p>Here's how I'd like to see it:</p> <pre><code>//in the ThreadPool class: public static bool QueueUserWorkItem&lt;T&gt; ( WaitCallback&lt;T&gt; callBack, T state ) public delegate void WaitCallback&lt;T&gt; (T state) </code></pre> <p>This would make the worker class type-safe (and a lot clearer, IMHO):</p> <pre><code>public class Worker&lt;T&gt; { public void schedule(T i_task) { ThreadPool.QueueUserWorkItem&lt;T&gt;(execute, i_task) } private void execute(T i_task){ //process i_task } } </code></pre> <p>I must be missing something.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload