这里有一个控制台程序,想要启动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 后,所有线程都在瞬间开始和结束。
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 ");
}
BeginInvoke
执行act
?为什么不直接将动作中的代码放在第一个回调中,并在结尾处调用OnTaskComplete
(因为如果我理解正确,回调已经在另一个线程上异步执行了)? - Cameron