惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Project Zero
Project Zero
月光博客
月光博客
Y
Y Combinator Blog
T
The Blog of Author Tim Ferriss
O
OpenAI News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Know Your Adversary
Know Your Adversary
Last Week in AI
Last Week in AI
S
Securelist
Engineering at Meta
Engineering at Meta
博客园 - 司徒正美
P
Privacy & Cybersecurity Law Blog
T
Tailwind CSS Blog
F
Fortinet All Blogs
博客园 - 三生石上(FineUI控件)
Scott Helme
Scott Helme
MyScale Blog
MyScale Blog
P
Proofpoint News Feed
云风的 BLOG
云风的 BLOG
C
Cisco Blogs
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
小众软件
小众软件
U
Unit 42
Microsoft Azure Blog
Microsoft Azure Blog
Hacker News: Ask HN
Hacker News: Ask HN
Hugging Face - Blog
Hugging Face - Blog
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
P
Proofpoint News Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
H
Hackread – Cybersecurity News, Data Breaches, AI and More
L
Lohrmann on Cybersecurity
IT之家
IT之家
Security Archives - TechRepublic
Security Archives - TechRepublic
I
InfoQ
S
Security @ Cisco Blogs
Webroot Blog
Webroot Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
F
Full Disclosure
D
Darknet – Hacking Tools, Hacker News & Cyber Security
The GitHub Blog
The GitHub Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
Jina AI
Jina AI
Cyberwarzone
Cyberwarzone
人人都是产品经理
人人都是产品经理
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
B
Blog RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - 许明会

异步编程,采用WorkgroupWorker,async和await关键字 OCR图像识别技术-Asprise OCR 关于委托,事件和类的设计准则 JavaScript能干什么? C#泛型代理、泛型接口、泛型类型、泛型方法 Delegate, Method as Parameter. DES对称性加密 通过Windows组策略限制证书组织流氓软件的安装运行 枚举\位域\结构综合实验 - 许明会 - 博客园 public static void Invoke (Action action) C#编写WIN32系统托盘程序 C#的互操作性:缓冲区、结构、指针 SQLServer异步调用,批量复制 Python体验(10)-图形界面之计算器 Python体验(09)-图形界面之Pannel和Sizer Python体验(08)-图形界面之工具栏和状态栏 Python体验(07)-图形界面之菜单 C#利用WIN32实现按键注册 Javascript猜数字游戏
利用委托实现异步调用
许明会 · 2016-03-29 · via 博客园 - 许明会
  1. 同步调用示例(委托是一个类型安全的,面向对象的指针)
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                int answer = op (10, 20);
                //after Add() executed, the folow goes on.
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }
    剖析代码的继承关系: 代理Operate经历了3次派生(绿色部分),实现了一个构造和3个虚拟函数(黄色部分).

    image
  2. 异步调用方法:线程异步了,但是主线程等待次线程返回才能获得结果,阻塞在EndInvoke上.
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke(10,20,null,null);
                Console.WriteLine ("Doing more in Main() exected immediately.");
                //the thread susppend on EndInvoke while 'result' is ready!
                int answer = op.EndInvoke (result);
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }

  3. 同步调用:如果线程没有返回,不要一直问何时返回,每间隔500ms做该做的事情!!!
    using System;
    using System.Threading;
    
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}\n", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}\n",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke(10,20,null,null);
                //while result is not OK, do it every 500 ms.
                while (!result.AsyncWaitHandle.WaitOne(500,true)) {//result.IsCompleted
                    Console.WriteLine ("Doing more work in Main().");
                }
                int answer = op.EndInvoke (result);
                Console.Write("After Add() executed, result = {0}",answer);
                Console.ReadKey ();
            }
        }
    }

  4. 线程回调: 好吧,干脆你返回的时候通知我,我该干啥不耽搁!
    using System;
    using System.Threading;
    
    /// <summary>
    /* Main() invoked on thread:1
    Main() execute no need to wait any more.
    Add() invoked on thread:3
    AddComplete() invoked on thread:3
    Your Addition is complete.
    */
    /// </summary>
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void AddComplete(IAsyncResult ia)
            {
                Console.WriteLine ("AddComplete() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Get Result value
                System.Runtime.Remoting.Messaging.AsyncResult ar=
                    (System.Runtime.Remoting.Messaging.AsyncResult)ia;
                Operate op = (Operate)ar.AsyncDelegate;
                Console.WriteLine ("The value is {0}.", op.EndInvoke (ia));
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke (10, 20, new AsyncCallback (AddComplete), null);
                Console.WriteLine ("Main() execute no need to wait any more.");
                Console.ReadKey ();
            }
        }
    }

  5. 主线程向次线程传递对象,通知!
    using System;
    using System.Threading;
    
    /// <summary>
    /*

    Main() invoked on thread:1
    Main() execute no need to wait any more.
    Add() invoked on thread:3
    AddComplete() invoked on thread:3
    The value is 30.
    The Main() thread is :1

    */
    /// </summary>
    namespace Demo
    {
        public delegate int Operate(int x, int y);
    
        public class DelegateAsync
        {
            static int Add(int a, int b)
            {
                Console.WriteLine ("Add() invoked on thread:{0}", 
                    Thread.CurrentThread.GetHashCode ());
                Thread.Sleep (5000);
                return a + b;
            }
    
            static void AddComplete(IAsyncResult ia)
            {
                Console.WriteLine ("AddComplete() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Get Result value
                System.Runtime.Remoting.Messaging.AsyncResult ar=
                    (System.Runtime.Remoting.Messaging.AsyncResult)ia;
                Operate op = (Operate)ar.AsyncDelegate;
                Console.WriteLine ("The value is {0}.", op.EndInvoke (ia));
                Thread thread = (Thread)ia.AsyncState;
                Console.WriteLine ("The Main() thread is :{0}", thread.GetHashCode());
            }
    
            static void Main()
            {
                Console.WriteLine ("Main() invoked on thread:{0}",
                    Thread.CurrentThread.GetHashCode ());
                //Add() call in Synchronouse mode
                Operate op = new Operate (Add);
                IAsyncResult result = op.BeginInvoke (10, 20, 
                    new AsyncCallback (AddComplete),Thread.CurrentThread);
                Console.WriteLine ("Main() execute no need to wait any more.");
                Console.ReadKey ();
            }
        }
    }

推荐下博客客户端工具: Download