Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# invoke

作者:慢靈魂   发布日期:2026-05-02   浏览:70

using System;
using System.Threading;

class Program
{
    delegate void MyDelegate(string message);

    static void Main()
    {
        MyDelegate myDelegate = new MyDelegate(PrintMessage);

        // 使用 Invoke 方法同步调用委托
        myDelegate.Invoke("This is a message using Invoke.");

        // 或者直接使用 () 调用委托,效果相同
        myDelegate("This is a message using direct call.");

        // 模拟异步调用
        Thread thread = new Thread(() =>
        {
            // 在另一个线程中调用委托
            myDelegate.Invoke("This is a message from another thread.");
        });

        thread.Start();
        thread.Join(); // 等待线程完成
    }

    static void PrintMessage(string message)
    {
        Console.WriteLine(message);
    }
}

解释说明

  1. 定义委托:

    • delegate void MyDelegate(string message); 定义了一个名为 MyDelegate 的委托类型,它接受一个字符串参数并且没有返回值。
  2. 创建委托实例:

    • MyDelegate myDelegate = new MyDelegate(PrintMessage); 创建了一个 MyDelegate 类型的委托实例,并将其绑定到 PrintMessage 方法。
  3. 同步调用委托:

    • myDelegate.Invoke("This is a message using Invoke."); 使用 Invoke 方法同步调用委托,传递一个字符串参数给 PrintMessage 方法。
    • 也可以直接使用 myDelegate("This is a message using direct call."); 来调用委托,效果与 Invoke 相同。
  4. 异步调用委托:

    • 在新线程中使用 Invoke 方法调用委托。thread.Start(); 启动新线程,thread.Join(); 等待线程完成。
  5. 方法实现:

    • static void PrintMessage(string message) 是一个简单的静态方法,用于输出传入的消息。

通过以上代码和解释,您可以理解如何在 C# 中使用 Invoke 方法来调用委托,无论是同步还是异步场景。

上一篇:c# timer

下一篇:c# 向上取整

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站