多线程编程——在线程中调用委托
首先编写一个调用委托的控制台程序如下:
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 delegete assunchronous call ");
r.AsyncWaitHandle.WaitOne();
string result = poolDelegate.EndInvoke(out threadid, r);
Console.WriteLine("thread pool worker thread id:{0}", threadid);
Console.WriteLine("123" + result);
Thread.Sleep(TimeSpan.FromSeconds(32));
}
private delegate string RunOnThreadPool(out int threadId);
private static void Callback(IAsyncResult ar)
{
Console.WriteLine("Starting a callback....");
Console.WriteLine("State pass 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);
}
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);
}
程序启动时,使用最古老的方式创建了一个线程。该线程调用方法Thread.CurrentThread.IsThreadPoolThread用来判断是否时线程池。
然后下面我们定义了一个委托调用BeginInvoke方法来运行该委托并接受一个回调函数,该函数会在异步操作完成后调用。当我们需要获取异步操作的结果的时候,就可以调用EndInvoke方法返回我们的结果。同时使用AsyncWaitHandle属性来等待操作直到完成。最后一句Thread.Sleep(TimeSpan.FromSeconds(32));不可注释,注释掉即我们的回调函数将不会被执行,因为主线程完成后所有的线程将会被终止。