程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> c# 關於Task類處理多線程的學習

c# 關於Task類處理多線程的學習

編輯:C#入門知識

 1.定義一個線程
 var task1 = Task.Factory.StartNew(() => DoSomeWork());
方法如下:
  View Code
        private static object DoSomeWork()
        {
            Console.WriteLine("nihao ");
            System.Threading.Thread.Sleep(3000);
            Console.Write("nihao ");
            return "xiexie";
        }

2.多線程執行後,執行另一個方法
  var task1 = Task.Factory.StartNew(() => DoSomeWork()).ContinueWith(
                 task => { Console.WriteLine(task.Result.ToString()); }).ContinueWith(
                 task => { Console.WriteLine(task.Result.ToString()); });
3.等待所有線程結束
var task1 = Task.Factory.StartNew(() => DoSomeWork());
var task2 = Task.Factory.StartNew(() => DoSomeWork());
var task3 = Task.Factory.StartNew(() => DoSomeWork());
Task.WaitAll(task1, task2, task3);
4.等待其中一個線程結束
var task1 = Task.Factory.StartNew(() => DoSomeWork());
var task2 = Task.Factory.StartNew(() => DoSomeWork());
var task3 = Task.Factory.StartNew(() => DoSomeWork());
Task.WaitAny(task1, task2, task3);
5.等待所有線程結束執行的方法
var task1 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(3000);
    return "dummy value 1";
});
 
var task2 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(3000);
    return "dummy value 2";
});
 
var task3 = Task.Factory.StartNew(() =>
{
    Thread.Sleep(3000);
    return "dummy value 3";
});
 
Task.Factory.ContinueWhenAll(new[] { task1, task2, task3 }, tasks =>
{
    foreach (Task<string> task in tasks)
    {
        Console.WriteLine(task.Result);
    }
});
 

摘自  無限遐想

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved