C# – Dynamically create thread

cmultithreading

I know how to use threads and background workers, but only in a "static" way (so hardcoding them). However I want to use something like this

public static void StartThread(string _Method)
{
    Thread t = new Thread(() => _Method;
    t.Start();
}

I know this will fail, due to _Method being a string. I've read using delegates but I'm not sure how this will work and if I need it in this case.

I want to start a thread for a specific function (so dynamically creating threads) when I need them.

Best Answer

You could use C# Task which is exactly what you need if you want to split work on different threads. Otherwise stay to Vlad's answer and use a method which accepts a delegate.

Task

Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));

Thread

public static Thread Start(Action action) {
    Thread thread = new Thread(() => { action(); });
    thread.Start();
    return thread;
}

// Usage
Thread t = Start(() => { ... });
// You can cancel or join the thread here

// Or use a method
Start(new Action(MyMethodToStart));