怪奇物语

怪奇物语

首页 新随笔 联系 管理

事件处理器 async void FunName() async ()=> {}

class Program
{
    static async Task Main()
    {
        var button = new Button();
        button.Click += Button_Click;
        button.SimulateClick();
        System.Console.WriteLine("do other things in Main method...");
        await Task.Delay(1000); // 等待事件处理完成
        System.Console.WriteLine("Main method completed.");
    }

    // 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
    // 事件处理器必须是 void 返回类型
    static async void Button_Click(object? sender, EventArgs e)
    {
        await Task.Delay(500);
        Console.WriteLine("Button clicked!");
    }
}

public class Button
{
    public event EventHandler? Click;

    public void SimulateClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}


class Program
{
    static async Task Main()
    {
        var button = new Button();


        // 👇👇👇👇👇👇👇👇👇👇👇👇👇👇👇
        button.Click += async (sender, args) =>
        {
            await Task.Delay(500);
            Console.WriteLine("Button clicked!");
        };

        button.SimulateClick();
        System.Console.WriteLine("do other things in Main method...");
        await Task.Delay(1000); // 等待事件处理完成
        System.Console.WriteLine("Main method completed.");
    }
}

public class Button
{
    public event EventHandler? Click;

    public void SimulateClick()
    {
        Click?.Invoke(this, EventArgs.Empty);
    }
}


posted on 2025-06-14 08:00  超级无敌美少男战士  阅读(10)  评论(0)    收藏  举报