C# 中的任务

csharpprogrammingserver side programming更新于 2025/9/25 2:52:17

任务在 C# 中表示异步操作。以下说明如何在 C# 中启动任务。

使用委托启动任务。

Task t = new Task(delegate { PrintMessage(); });
t.Start();

使用任务工厂启动任务。

Task.Factory.StartNew(() => {Console.WriteLine("Welcome!"); });

您也可以使用 Lambda。

Task t = new Task( () => PrintMessage() );
t.Start();

启动任务最基本的方法是使用 run()。

示例

using System;
using System.Threading.Tasks;

public class Example {
   public static void Main() {
      Task task = Task.Run( () => {
         int a = 0;
         for (a = 0; a <= 1000; a++){}
         Console.WriteLine("{0} loop iterations ends",a);
      } );
      task.Wait();
   }
}

相关文章