【发布时间】:2020-06-05 08:13:17
【问题描述】:
我想制作一个包含 2 个线程的程序,每次触发计时器时都会重复调用这些线程。
我知道您在技术上无法重新启动线程,但我想知道是否有任何解决方法可以解决此问题?
using System;
using System.Threading;
public class Program {
// static method one
static void method1()
{
// some code here
}
// static method two
static void method2()
{
// some code here
}
// Main Method
public void Main()
{
// Creating and initializing timer
System.Timers.Timer MyTimer = new System.Timers.Timer();
MyTimer.Interval = 4000;
MyTimer.Tick += new EventHandler(timer1_Tick);
MyTimer.Start();
autoResetEvent = new AutoResetEvent(false);
// Creating and initializing threads
Thread thr1 = new Thread(method1);
Thread thr2 = new Thread(method2);
thr1.Start();
thr2.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
// code below is wrong. I want to repeat/restart the threads
thr1.Start();
thr2.Start();
}
}
【问题讨论】:
-
线程就像生物一样。一旦他们结束,他们就结束了。如果你想重用它们,你必须专门让它们保持活力。您是否特别需要使用相同的线程?
-
如果在第二个
Tick事件发生时,一个或两个线程仍在从第一个Tick事件运行,您希望发生什么? -
视情况而定。你希望你的任务重复吗?或者你假设你的任务被打断了?如果
Task不适合您的用例,您可以编辑您的帖子。
标签: c# multithreading timer