沒想到要在 C# 中使用, Thread Pool 這麼簡單.
如下簡單範例, 當然實際的程式不可能這樣, 但這是一個好入門概念.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadPoo
{
class ThreadPool1
{
static void Main(string[] args)
{
System.Threading.WaitCallback waitCallback = new WaitCallback(MyThreadWork);
ThreadPool.QueueUserWorkItem(waitCallback, "First");
ThreadPool.QueueUserWorkItem(waitCallback, "Second");
ThreadPool.QueueUserWorkItem(waitCallback, "Third");
Console.WriteLine("Main thread exits.");
Console.ReadKey();
}
static void MyThreadWork(object state)
{
Console.WriteLine("Begin of {0}", (string)state);
Thread.Sleep(5000);
Console.WriteLine("End of {0}", (string)state);
}
}
}
輸出結果 :
Main thread exits.
Begin of First
Begin of Third
Begin of Second
End of First
End of Third
End of Second
如果想要使用匿名委派, 也可以這樣寫.
namespace ThreadPoo
{
class ThreadPool1
{
static void Main(string[] args)
{
ThreadPool.QueueUserWorkItem(delegate
{
Console.WriteLine("Begin of {0}", "First");
Thread.Sleep(5000);
Console.WriteLine("End of {0}", "First");
});
Console.WriteLine("Main thread exits.");
Console.ReadKey();
}
}
}
如果想要用 Lambda 方式可以改成, 很簡單, 只是一種語法而已.
ThreadPool.QueueUserWorkItem(callback =>
{
Console.WriteLine("Begin of {0}", "First");
Thread.Sleep(5000);
Console.WriteLine("End of {0}", "First");
});
問題來了, 如果 call back function 必須由 caller 傳入一些資訊呢? 可以改成這樣.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ThreadPoo
{
public class TaskInfo
{
public string Who;
public TaskInfo(string Value)
{
Who = Value;
}
}
class ThreadPool2
{
static void Main(string[] args)
{
TaskInfo ti = new TaskInfo("Jack");
ThreadPool.QueueUserWorkItem(new WaitCallback(MyThreadWork), ti);
Thread.Sleep(1000);
Console.WriteLine("Main thread exits.");
Console.ReadKey();
}
static void MyThreadWork(object state)
{
TaskInfo ti = (TaskInfo)state;
Console.WriteLine("Begin of {0}", ti.Who);
Thread.Sleep(5000);
Console.WriteLine("End of {0}", ti.Who);
}
}
}
輸出結果 :
Begin of Jack
Main thread exits.
End of Jack