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

    事情是这样的,我看到了以下的一段代码,才引发了对这个问题的思考。代码如下:

     1 using UnityEngine;
     2 using UnityEditor;
     3 
     4 public class CustomInspector : Editor
     5 {
     6     protected void WrapWithValidationColor(System.Action method, bool isValid, bool isValidWarning)
     7     {
     8         Color colorBackup = GUI.color;
     9         if (isValid == false)
    10         {
    11             GUI.color = Color.red;
    12         }
    13         else if (isValidWarning == false)
    14         {
    15             GUI.color = Color.yellow;
    16         }
    17         method.Invoke();
    18         GUI.color = colorBackup;
    19     }
    20 }

    就是看到第 17 行时候,我去查了一下相关资料,引发了对这个问题的思考。

    看测试代码:

     1 using System;
     2 using System.Threading;
     3 
     4 namespace CSharpTest
     5 {
     6     class Program
     7     {
     8         delegate void LugsTest();
     9 
    10         static void Main(string[] args)
    11         {
    12             LugsTest lt = new LugsTest(ThreadSleep);
    13             lt.Invoke();                        // 3s 后才打印
    14             //lt.BeginInvoke(null, null);       //立即打印
    15             Console.WriteLine("LugsTest()");
    16             Console.ReadKey();
    17         }
    18 
    19         static void ThreadSleep()
    20         {
    21             Thread.Sleep(3000);
    22         }
    23     }
    24 }

    具体的执行结果,注释中写有,而两者的区别就是:

    Invoke 是在主线程中执行,BeginInvoke 是另开一个线程执行。

  • 相关阅读:
    adb shell top
    数据清洗的方法
    Devices Tree加载流程
    Android驱动之设备树简介
    序列模式挖掘综述
    python 实现kmeans聚类
    numpy中sum(axis=0)和axis=1的计算原理
    win7 VMware下安装centos和Ubuntu共存
    python数据标准化
    python 用PIL Matplotlib处理图像的基本操作
  • 原文地址:https://www.cnblogs.com/luguoshuai/p/10940879.html
Copyright © 2011-2022 走看看