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();
t1.Wait();
t2.Wait();
System.Console.WriteLine(num);
System.Console.WriteLine("hello word");
System.Console.ReadKey();
}
public static void fun() {
for (int i = 0; i < 10; i++) {
Thread.Sleep(10);
num++;
}
}
}
}
2.运行结果

本文通过一个C#代码示例展示了如何使用Task进行多线程操作,并同步控制线程执行,最终输出变量num的累加结果。在示例中,两个Task分别调用fun函数进行累加操作,确保所有任务完成后输出结果。
474

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



