zoukankan      html  css  js  c++  java
  • 多线程编程——在线程中调用委托

    首先编写一个调用委托的控制台程序如下:

    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));不可注释,注释掉即我们的回调函数将不会被执行,因为主线程完成后所有的线程将会被终止。

  • 相关阅读:
    idea资源导出失败的问题
    计算机的运算方法
    ajax返回json字符串,前端显示中文乱码问题解决
    解决xml编码问题:1 字节的 UTF8 序列的字节 1 无效
    【转】erlang四种监控策略one_for_one、one_for_all、simple_one_for_one、rest_for_one
    erlang:register and global:register_name
    【转】重点介绍erlang的global模块
    memset函数用法
    简单实现SQL Server 2012高可用性组
    《mysql必知必会》读书笔记游标的使用
  • 原文地址:https://www.cnblogs.com/a2502971/p/13698110.html
Copyright © 2011-2022 走看看