C# 事件 委托 同步 异步
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Configuration;
using System.IO.Pipes;
using System.Threading;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
test += new Testdelegate(test1);//事件赋值
test+=new Testdelegate( test2);//事件赋值
}
string msg = "";
string test1(DelegateEventArgs e)
{
for (int i = 1; i <= 100;i++ )
{
msg += i.ToString() + ",";
Thread.Sleep(100);
}
return "";
}
string test2(DelegateEventArgs e)
{
for (int i = 101; i <= 200;i++ )
{
msg += i.ToString() + ",";
Thread.Sleep(100);
}
return "";
}
//定义事件
private event Testdelegate test;
private void button2_Click(object sender, EventArgs e)
{
msg = "";
if (test!=null)
{
//异步执行事件里的委托链
foreach (Testdelegate t in test.GetInvocationList())
{
DelegateEventArgs a = new DelegateEventArgs("");
t.BeginInvoke(a, null, null);
}
//同步执行事件里的委托
//DelegateEventArgs b = new DelegateEventArgs("");
//test(b);
}
}
private void button3_Click(object sender, EventArgs e)
{
MessageBox.Show(msg);
}
}
//定义委托参数
public class DelegateEventArgs : EventArgs
{
string str_response;
public DelegateEventArgs(string ls_res)
{
this.str_response = ls_res;
}
}
//定义委托规格
public delegate string Testdelegate(DelegateEventArgs e);
}