我知道如何使用线程和后台工作程序,但只能以"静态"方式(所以硬编码).但是我想用这样的东西
public static void StartThread(string _Method)
{
Thread t = new Thread(() => _Method;
t.Start();
}
Run Code Online (Sandbox Code Playgroud)
我知道这会失败,因为它_Method是一个字符串.我已阅读使用,delegates但我不确定这将如何工作,如果我需要它在这种情况下.
我想在需要时启动特定功能的线程(以便动态创建线程).
您可以使用C#Task,如果您想在不同的线程上拆分工作,这正是您所需要的.否则留下弗拉德的答案并使用接受代表的方法.
Task.Factory.StartNew(() => Console.WriteLine("Hello from taskA."));
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)