gpt4 book ai didi

c# - 动态创建线程

转载 作者:太空狗 更新时间:2023-10-29 22:14:27 25 4
gpt4 key购买 nike

我知道如何使用线程和后台 worker ,但只能以“静态”方式使用(因此对它们进行硬编码)。但是我想用这样的东西

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

我知道这会失败,因为 _Method 是一个字符串。我读过使用 delegates 但我不确定这将如何工作以及在这种情况下是否需要它。

我想在需要时为特定功能启动一个线程(因此动态创建线程)。

最佳答案

你可以使用 C# Task如果您想在不同线程上拆分工作,这正是您所需要的。否则请继续使用 Vlad 的回答并使用接受委托(delegate)的方法。

任务

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

线程

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));

关于c# - 动态创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10313185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com