第一步,委托的申明
private delegate string RunOnThreadPool(out int threadId);
第二步,将被作为线程运行的函数
private static string Test(out int threadId)
{
Console.WriteLine("starting...");
Console.WriteLine("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Thread.Sleep(TimeSpan.FromSeconds(2));
threadId = Thread.CurrentThread.ManagedThreadId;
return string.Format("thread pool worker thread id was:{0}", threadId);
}
第三步,回调函数
private static void Callback(IAsyncResult ar)
{
Console.WriteLine("starting a callback...");
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.WriteLine("starting passed to a callback:{0}", ar.AsyncState);
Console.WriteLine("is thread pool thread: {0}", Thread.CurrentThread.IsThreadPoolThread);
Console.WriteLine("thread pool worker thread id: {0}", Thread.CurrentThread.ManagedThreadId);
}
第四步,主函数
static void Main(string[] args)
{
int threadId = 0;
// 申明对函数的引用
RunOnThreadPool poolDelegate = Test;
var t = new Thread(() => Test(out threadId));
t.Start();
t.Join();
Console.WriteLine("thread id: {0}", threadId);
//回调函数在委托函数调用结束后开始
IAsyncResult r = poolDelegate.BeginInvoke(out threadId, Callback, "a delegate asynchronous call");
//等待,直到线程结束
r.AsyncWaitHandle.WaitOne();
//while(!r.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(0.1)))
//{
// Console.Write("*");
//}
//获取线程运行结束后的结果
string result = poolDelegate.EndInvoke(out threadId, r);
Console.WriteLine("thread pool worker thread id: {0}", threadId);
Console.WriteLine(result);
Thread.Sleep(TimeSpan.FromSeconds(2));
Console.ReadKey();
}