Starting Any Method in a New Thread Using .NET

The main problem I encountered was creating a function to accept any function pointer along with an unknown number of arguments.  I got around this problem using the ThreadStart and delegate() features in C# (.NET 3.5).  First off create your method to take any method as so:

public static Thread StartMethodInNewThread(ThreadStart methodToStart)
{
    // Do common some stuff before starting the thread, such as logging.

    // Start the task in a new thread
    Thread t = new Thread(methodToStart);
    t.Start();

    // Do some stuff after starting the thread, such as more logging.

    // If the caller cares you can return the thread.
    return t;
}

Now anywhere in your code where you need to start a new method in a thread write the following:

[Read More]
Categories: code-examples  Tags: net threads