.Net Task 與 Thread 範例 差異 基本操作 .Net Task 與 Thread 範例 差異 基本操作
  .NET       ez      2013-01-25

Task 與 Thread 的基本使用方法。

執行結果:

範例程式碼:

//傳統寫法
List<Thread> Pool = new List<Thread>();
for (int i = 0; i < 5; i++)
{
    Pool.Add(new Thread((object str) =>
    {
        Thread.Sleep(i * 500);
        Console.WriteLine("Thread " + ((string)str).ToString());
    }));
}
for (int i = 0; i < 5; i++) Pool[i].Start(i.ToString());
Console.WriteLine("Thread Start!");
for (int i = 0; i < 5; i++) Pool[i].Join();
Console.WriteLine("Thread Done!");
Console.ReadLine();
List<Task> PoolTask = new List<Task>();
for (int i = 0; i < 5; i++)
{
    int x = i;
    PoolTask.Add(Task.Factory.StartNew(() =>
    {
        Thread.Sleep(1000);
        Console.WriteLine("Task " + x.ToString());
    }));
}
Console.WriteLine("Task Start!");
Task.WaitAll(PoolTask.ToArray());
Console.WriteLine("Thread Done!");
Console.ReadLine();
List<Task<string>> PoolTaskReturn = new List<Task<string>>();
for (int i = 0; i < 5; i++)
{
    int x = i;
    PoolTaskReturn.Add(Task.Factory.StartNew<string>(() =>
    {
        Thread.Sleep(1000);
        return "Task Return " + x.ToString();
    }));
}
Console.WriteLine("Task Start!");
for (int i = 0; i < 5; i++) Console.WriteLine(PoolTaskReturn[i].Result);
Console.WriteLine("Thread Done!");
Console.ReadLine();
Task.Factory.StartNew(() =>
{
    Thread.Sleep(1000);
    Console.WriteLine("Task A");
}).ContinueWith(task =>
{
    Thread.Sleep(1000);
    Console.WriteLine("Task B");
}).ContinueWith(task =>
{
    Thread.Sleep(1000);
    Console.WriteLine("Task C");
}).ContinueWith(task =>
{
    Thread.Sleep(1000);
    Console.WriteLine("Task D");
});
Console.ReadLine();

標籤:   .NET

我要留言