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 是另开一个线程执行。

  • 相关阅读:
    gcc编译常用选项
    汇编指令随笔
    VIM简单操作
    Linux编译阻塞型驱动遇到'TASK_NORMAL' undeclared (first use in this function)问题解决办法
    Linux中断流程分析
    Linux驱动开发之LED驱动
    函数(三)
    函数(二)
    文件和函数(一)
    文件处理和字符编码
  • 原文地址:https://www.cnblogs.com/luguoshuai/p/10940879.html
Copyright © 2011-2022 走看看