Here is a console program want 10 threads start in batch, wait 5 seconds, and stop in batch.
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);
}
but the result is not what I expected, 10 threads start one-by-one SLOWLY(around 1 second interval), even some "finish" comes out before some "start".
when comment out Thread.Sleep, all threads start and finish in flash.
Does Thread.Sleep
affect other threads? Is there anyway to make a pure idle time?
/-----------------------------edit-----------------------------
same problem also happen in:
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();
}
----------------------Edit------------------------
finally I found a lovely way to substitute 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 ");
}