正常情况
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeginInvokeTest
{
internal class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.Printed += T_Printed;
t.Call("fjds");
Console.ReadLine();
}
private static void T_Printed(string obj)
{
Console.WriteLine("T_Printed:" + obj);
}
}
public class Test
{
public event Action<string> Printed;
public void Call(string s)
{
this.Printed?.BeginInvoke(s, null, null);
}
}
}
此时正常输出fjds
出错情况
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BeginInvokeTest
{
internal class Program
{
static void Main(string[] args)
{
Test t = new Test();
t.Printed += T_Printed;
t.Printed += T_Printed2;
t.Call("fjds");
Console.ReadLine();
}
private static void T_Printed2(string obj)
{
Console.WriteLine("T_Printed2:" + obj);
}
private static void T_Printed(string obj)
{
Console.WriteLine("T_Printed:" + obj);
}
}
public class Test
{
public event Action<string> Printed;
public void Call(string s)
{
this.Printed?.BeginInvoke(s, null, null);
}
}
}
这个仅仅比上面多绑定了一个方法就报错了。
将上述的Printed
由事件改成委托,一样报错
结论
使用事件或者委托的BeginInvoke
需要注意:如果事件或者委托可能绑定多个方法,不能用BeginInvoke,需要使用Invoke