zoukankan      html  css  js  c++  java
  • C#中Invoke和BeginInvoke的区别

    1、Invoke() 调用时,Invoke会阻止当前主线程的运行,等到 Invoke() 方法返回才继续执行后面的代码,表现出“同步”的概念。

    2、BeginInvoke() 调用时,当前线程会启用线程池中的某个线程来执行此方法,BeginInvoke不会阻止当前主线程的运行,而是等当前主线程做完事情之后再执行BeginInvoke中的代码内容,表现出“异步”的概念。在想获取 BeginInvoke() 执行完毕后的结果时,调用EndInvoke() 方法来获取。而这两个方法中执行的是一个委托。

    测试代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace InvokeDemo
    {
        class Program
        {
            //代理
            private delegate int Mydelegate(int a, int b);
    
            static void Main(string[] args)
            {
                Console.WriteLine("Invoke开始,时间:" + DateTime.Now);
                Console.WriteLine("主线程ID:" + Thread.CurrentThread.ManagedThreadId);
                Mydelegate myd = new Mydelegate(Fun);
                var result = myd.Invoke(1, 2);
                Console.WriteLine("计算结果:" + result);
                Console.WriteLine("Invoke结束,时间:" + DateTime.Now);
    
                Console.WriteLine();
                Console.WriteLine("------分割线------");
                Console.WriteLine();
    
                Console.WriteLine("BeginInvoke开始,时间:" + DateTime.Now);
                Mydelegate mydSync = new Mydelegate(Fun);
                mydSync.BeginInvoke(1, 2, new AsyncCallback(AsyncCallback), mydSync);
                Console.WriteLine("BeginInvoke结束,时间:" + DateTime.Now);
    
                Console.Read();
            }
    
            static int Fun(int a, int b)
            {
                Thread.Sleep(3000);
                Console.WriteLine("方法线程ID:" + Thread.CurrentThread.ManagedThreadId);
                return a + b;
            }
    
            static void AsyncCallback(IAsyncResult asyncResult)
            {
                var del = (Mydelegate)asyncResult.AsyncState;
                var funResult = del.EndInvoke(asyncResult);
                Console.WriteLine("计算结果:" + funResult);
            }
        }
    }

    结果:

    可以看出:

    Invoke方法中线程ID跟主线程ID一致,表现是阻塞的。

    InvokeBegin方法中线程ID跟主线程ID不一致,表现是异步的。

  • 相关阅读:
    #Leetcode# 219. Contains Duplicate II
    #Leetcode# 203. Remove Linked List Elements
    #Leetcode# 141. Linked List Cycle
    #Leetcode# 128. Longest Consecutive Sequence
    linux——shell解释
    Linux——互联网搜索引擎nbtscan是一个扫描WINDOWS网络NetBIOS信息的小工具
    Linux——网络端口的状态netstat、ifconfig
    连不上网的原因
    jquery基础笔记
    网址收藏
  • 原文地址:https://www.cnblogs.com/zhuyongblogs/p/5707097.html
Copyright © 2011-2022 走看看