这个用法很简单
我有这个来启动线程
主班
for (int x = 1; x <= numThreads; x++)
{
new ThreadComponent(x, this, creator).init();
}线程类
public void init()
{
thread = new Thread(doLogic);
thread.IsBackground = true;
thread.Start();
}
void doLogic()
{
while (true)
{
doLogicGetData();
}
}这个想法是线程执行需要大约。6秒,我想要6个线程,从1秒间隔开始
1------1------
2------2------
3------3------
4------4------
5------5------
6------6------ 我看到了很多关于使用计时器或cron作业的想法,但我不知道如何正确地实现它们。
发布于 2020-09-25 09:54:49
在.Net中解决这个问题的一个更“规范”的方法是使用任务并行库而不是手动控制线程。下面的控制台程序演示了如何在后台线程上运行6个线程,在它们之间延迟一秒钟。
class Program
{
public async static Task Main()
{
var cts = new CancellationTokenSource();
List<Task> tasks = new List<Task>();
for (int i = 0; i < 6; i++)
{
tasks.Add(Task.Run(() => DoWork(cts.Token), cts.Token));
await Task.Delay(1000);
}
Console.WriteLine("Press ENTER to stop");
Console.ReadLine();
Console.WriteLine("Waiting for all threads to end");
cts.Cancel();
await Task.WhenAll(tasks);
}
public static void DoWork(CancellationToken token)
{
while (!token.IsCancellationRequested)
{
Console.WriteLine($"Doing work on thread {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(10000); // simulating 10 seconds of CPU work;
}
Console.WriteLine($"Worker thread {Thread.CurrentThread.ManagedThreadId} cancelled");
}
}在文件中很好地解释了使用任务并行库的异步编程
https://stackoverflow.com/questions/64061245
复制相似问题