I ran across a scenario where I needed to call dynamically created Action’s in a threaded manner, and was surprised at how simple the code was to do it:
public static void QueueAction(Action action)
{
System.Threading.WaitCallback callback = state => action();
System.Threading.ThreadPool.QueueUserWorkItem(callback);
}
Which can then be called in a variety of ways:
Action action = delegate() { System.Threading.Thread.Sleep(1000); };
QueueThread(action);
QueueThread(() => System.Threading.Thread.Sleep(1000));
QueueThread(randomUnknownMethod);
I won’t make the claim that this is “production worthy” code, but if you’re looking for a quick way to execute an Action on a new thread, it does a pretty fine job. One thing to note: I used the ThreadPool in this example as it’s typically safer than firing up new Threads from the Thread object, but feel free to improvise.
- Colin
3f8f76b0-c90f-4620-b7ec-7a88f06b634a|1|4.0