1.代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
public static int num = 0;
static void Main(string[] args)
{
var t1 = new Task(fun);
t1.Start();
var t2 = new Task(fun);
t2.Start();
while (true) {
if (t1.IsCompleted && t2.IsCompleted)
{
System.Console.WriteLine(num);
break;
}
}
System.Console.WriteLine("hello word");
System.Console.ReadKey();
}
public static void fun() {
for (int i = 0; i < 10; i++) {
Thread.Sleep(1000);
num++;
}
}
}
}
2.运行效果

本文探讨了使用C#编程语言中的Task和Thread实现并发任务的基本原理。通过实例展示了如何创建并启动两个独立任务,以及如何通过while循环检测任务完成。重点在于线程同步和控制台输出的演示。
1648

被折叠的 条评论
为什么被折叠?



