多线程编程——在线程中调⽤委托
⾸先编写⼀个调⽤委托的控制台程序如下:writeline函数
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 ");
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("");
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));不可注释,注释掉即我们的回调函数将不会被执⾏,因为主线程完成后所有的线程将会被终⽌。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。