工作中需要进行多线程操作,写了一个简单的程序测试Task.Factory.StartNew后面加wait和不加wait的区别。
简单来讲,如果加wait就是串行,如果不加wait就是并行。
namespace 多线程测试
{
class Program
{
static private CancellationTokenSource cts;
static private List<Task> taskPool;
static void WriteLine(object line)
{
Console.WriteLine(DateTime.Now.ToString("mm:ss.ffff") + " " + line);
}
static private void Test(int channel)
{
WriteLine("Task Start " + channel.ToString());
Thread.Sleep(1000);
WriteLine("Task End " + channel.ToString());
}
static private void BeginTest1()
{
cts = new CancellationTokenSource();
taskPool = new List<Task>();
for (int channel = 1; channel <= 8; channel++)
{
if (!cts.IsCancellationRequested)
Task.Factory.StartNew((i) => Test((int)i), channel, cts.Token).Wait();
}
}
static private void BeginTest2()
{
cts = new CancellationTokenSource();
taskPool = new List<Task>();
for (int channel = 1; channel <= 8; channel++)
{
if (!cts.IsCancellationRequested)
Task.Factory.StartNew((i) => Test((int)i), channel, cts.Token);
}
}
static void Main(string[] args)
{
BeginTest1();
Console.WriteLine("=========================");
BeginTest2();
Console.ReadKey();
}
}
}
测试结果如下
47:25.3058 Task Start 1
47:26.3178 Task End 1
47:26.3178 Task Start 2
47:27.3241 Task End 2
47:27.3243 Task Start 3
47:28.3339 Task End 3
47:28.3339 Task Start 4
47:29.3393 Task End 4
47:29.3393 Task Start 5
47:30.3431 Task End 5
47:30.3433 Task Start 6
47:31.3497 Task End 6
47:31.3497 Task Start 7
47:32.3512 Task End 7
47:32.3514 Task Start 8
47:33.3553 Task End 8
=========================
47:33.3559 Task Start 1
47:33.3559 Task Start 2
47:33.3559 Task Start 4
47:33.3559 Task Start 3
47:33.3569 Task Start 5
47:33.3579 Task Start 6
47:33.3579 Task Start 7
47:33.3589 Task Start 8
47:34.3634 Task End 1
47:34.3634 Task End 4
47:34.3634 Task End 5
47:34.3634 Task End 2
47:34.3634 Task End 7
47:34.3634 Task End 3
47:34.3634 Task End 6
47:34.3634 Task End 8