這範例是從這邊改編的
https://msdn.microsoft.com/zh-tw/library/system.threading.tasks.task.factory(v=vs.110).aspx
public static void Main(string[] args)
{
Task[] tasks = new Task[2];
String[] files = new string[3];
String[] dirs = new string[3];
tasks[0] = Task.Factory.StartNew(() => files = ProduceArray());
tasks[1] = Task.Factory.StartNew(() => dirs = ProduceArray());
//上面task就開始跑了
//這邊先直接印結果
Console.WriteLine("{0} contains: ", "Result");
Console.WriteLine(" {0} subdirectories", dirs.Length);
Console.WriteLine(" {0} files", files.Length);
//這邊會等alltask完成才印結果
Task.Factory.ContinueWhenAll(tasks, completedTasks =>
{
Console.WriteLine("{0} contains: ", "Result");
Console.WriteLine(" {0} subdirectories", dirs.Length);
Console.WriteLine(" {0} files", files.Length);
});
Console.Read();
}
//花較多時間產生陣列的方法,要花時間才意看出差別
public static string[] ProduceArray()
{
int j = 3000000;
string[] s = new string[j];
for (int i = 0; i < j; i++)
{
s[i] = "hi"+i.ToString();
}
return s;
}
結果
Result contains:
3 subdirectories
3 files
//上面下面同樣印dirs和files,
上面會馬上印出,代表task執行試另外執行緒在跑的是異步的,
不然同步的化應該要等task跑完才ˋ執行到這邊
//下面這邊會等個幾秒才跑出來,代表真的是等所有task結束才印
Result contains:
3000000 subdirectories
3000000 files
留言列表