Showing posts with label threadpool. Show all posts
Showing posts with label threadpool. Show all posts

November 10, 2018

ThreadPool Extensions

A better more versatile way to do this is to use Task<> objects
public static class ThreadpoolExtensions
{
    // Execute a method/procedure on the thread pool
    // The state parameters allow you to pass parameters into the thread routine 
    public static bool ExecuteOnThreadPoolThread<T>(this Action<T> threadRoutine, T args)
    {
        return ThreadPool.QueueUserWorkItem(s => threadRoutine((T)s), args);
    }

    // Execute a method/procedure on the thread pool
    public static bool ExecuteOnThreadPoolThread(this Action threadRoutine)
    {
        return ThreadPool.QueueUserWorkItem((obj) => threadRoutine());
    }
}

February 4, 2013

A Generic ThreadPool.QueueUserWorkItem

Found the idea here
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

January 13, 2006

Threading using the ThreadPool

Use something along the lines:
System.Threading.ThreadPool.QueueUserWorkItem(
new System.Threading.WaitCallback(MyThreadRoutine), stateObject);
where 'stateObject' is an object which is passed as a parameter to the thread routine 'MyThreadRoutine'
For a generic version look here