这是一个控制台程序,希望 10 个线程批量启动,等待 5 秒,然后批量停止。
static void Main(string[] args)
{
System.Threading.Tasks.Parallel.For(0, 10, (index) =>
{
Action<int> act = (i) =>
{
Console.Write("start {0} ", i);
Thread.Sleep(5000);
};
act.BeginInvoke(index, OnTaskComplete, index);
});
Console.ReadKey();
}
static void OnTaskComplete(IAsyncResult res)
{
Console.Write("finish {0} ", res.AsyncState);
}
但结果不是我所期望的,10个线程一个接一个地缓慢启动(大约1秒间隔),甚至在一些“开始”之前出现了一些“完成”。
当注释掉 Thread.Sleep 时,所有线程都在闪存中开始和结束。
Does Thread.Sleep
影响其他线程?有什么办法可以让自己有一段纯粹的空闲时间吗?
/ - - - - - - - - - - - - - - -编辑 - - - - - - - - - - ----------
同样的问题也发生在:
static void Main(string[] args)
{
System.Threading.Tasks.Parallel.For(0, 10, (index) =>
{
Console.Write("start {0} ", index);
Thread.Sleep(5000);
Console.Write("fnish {0} ", index);
});
Console.ReadKey();
}
- - - - - - - - - - - 编辑 - - - - - - - - - - - -
最后我找到了一个可爱的方法来替代 thread.sleep
static void Main(string[] args)
{
System.Threading.Tasks.Parallel.For(0, 10, (index) =>
{
Console.Write("start {0} ", index);
var t1 = new System.Threading.Timer(new TimerCallback(MyTimerCallback), index, 5000, 0);
});
Console.ReadKey();
}
static void MyTimerCallback(object o)
{
Console.Write("Timer callbacked ");
}