事件处理器 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);
}
}