Found the idea here
A generic version of the "ThreadPool.QueueUserWorkItem" method. I believe that this really belongs in the .NET framework
A generic version of the "ThreadPool.QueueUserWorkItem" method. I believe that this really belongs in the .NET framework
// Generic QueueUserWorkItem implementation, the thread routine signature
public delegate void ThreadRoutine<T>(T state);
/// <summary>
/// Extensions to the ThreadPool class
/// </summary>
public static class ThreadPoolExtender
{
/// <summary>
/// Queue specified thread routine/work item for processing
/// on a thread pool thread.
/// </summary>
/// <typeparam name="T">Thread routine parameter type.</typeparam>
/// <param name="state">object containing state for the thread
/// routine.</param>
/// <param name="threadRoutine">Thread routine/work item to queue
/// that shall be executed on a thread pool thread</param>
/// <returns>indicates success.</returns>
public static bool QueueUserWorkItem<T>(T state, ThreadRoutine<T> threadRoutine)
{
return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), state);
}
}
Sample usage with an an anonymous object
res = ThreadPoolExtender.QueueUserWorkItem(
// Anonymous type, saves defining a class type just for this call
new { onFinishedDelegate = onFinished, Folderpath = folderPath },
(input) => // input matches the anonymous object defined in the line above
{ // Start worker thread work
bool outcome = this.DoSomething(input.Folderpath);
// In this example we callback on a delegate to indicate that
// the thread work is complete
input.onFinishedDelegate(outcome);
}); // End worker thread work
No comments:
Post a Comment