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

  • 相关阅读:
    router.beforeEach、路由元信息、导航守卫与函数式编程
    C++传递不定参函数
    函数式编程-compose与pipe
    玩转redux--从会用到庖丁解牛
    redux沉思录:基于flux、状态管理、函数式编程的前端状态管理框架
    Laravel 框架集成 UEditor 编辑器的方法
    i18n实现前端国际化(实例)
    laravel获取当前认证用户登录
    larave5.6 引入自定义函数库时,报错不能重复定义
    2019教师证教材资料
  • 原文地址:https://www.cnblogs.com/a2502971/p/13698110.html
Copyright © 2011-2022 走看看