C# -- 使用 Task 执行多线程任务
1. 使用 Task 执行多线程任务
class Program
{
static void Main(string[] args)
{
Task task1 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); Task task2 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); Task task3 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); task1.Start();
task2.Start();
task3.Start(); Console.ReadKey();
} static long SumNumbers(int count)
{
long sum = ;
for (int i = ; i < count; i++)
{
sum += i;
}
Thread.Sleep();
return sum;
}
}
执行结果:
2. 等待Task多线程任务执行完成
class Program
{
static void Main(string[] args)
{
Task task1 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); Task task2 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); Task task3 = new Task(() => {
Console.WriteLine("线程ID:{0},开始执行", Thread.CurrentThread.ManagedThreadId);
Stopwatch stw = new Stopwatch();
stw.Start();
long result = SumNumbers();
stw.Stop();
Console.WriteLine("线程ID:{0},执行完成,执行结果:{1},执行用时{2},", Thread.CurrentThread.ManagedThreadId, result, stw.ElapsedMilliseconds);
}); List<Task> listTask = new List<Task>();
listTask.Add(task1);
listTask.Add(task2);
listTask.Add(task3); task1.Start();
task2.Start();
task3.Start(); Task.WaitAll(listTask.ToArray());
Console.WriteLine("所有线程执行完成。"); Console.ReadKey();
} static long SumNumbers(int count)
{
long sum = ;
for (int i = ; i < count; i++)
{
sum += i;
}
Thread.Sleep();
return sum;
}
}
执行结果: