Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create thread

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.

like image 767
Devator Avatar asked Apr 25 '12 09:04

Devator


1 Answers

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));
like image 132
Felix K. Avatar answered Oct 03 '22 23:10

Felix K.