Home > Article > Backend Development > Task usage startup method example
class Program { static void Main(string[] args) { Task t = new Task(DoA); t.Start(); Console.ReadKey(); } static void DoA() { for (int i = 0; i < 100; i++) { Console.WriteLine("i={0}\n", i); } } }
2) Run directly through Run, accept The parameter is an Action, and the return object is a Task
static void Main(string[] args) { Task.Run(() => { for (int i = 0; i < 50; i++) { Console.WriteLine("i={0}",i); } }); Console.ReadKey(); }
3) Thread with return parameters
Task<int> task = Task.Run<int>(() => { int sum = 0; for (int i = 0; i < 50; i++) { sum += 1; } return sum; }); int result = task.Result; Console.WriteLine("运算结果是:{0}",result);//输出50 Console.ReadKey();
4) Through Task.Factory
Task t = Task.Factory.StartNew(() => { for (int i = 0; i < 10; i++) { Console.WriteLine("i={0}", i); } });
The above is the detailed content of Task usage startup method example. For more information, please follow other related articles on the PHP Chinese website!