C# 委托的使用

 利用委托进行异步操作

1:定义一个委托,int是委托的函数的返回值类型,如果是void就写void
public delegate int ListenServerDelegate();

2:创建一个委托,GetServerList是函数
ListenServerDelegate listenServerDelegate = new ListenServerDelegate(GetServerList);

3:开始执行委托的函数,str是GetServerList的参数,如果无参就不写
this.BeginInvoke(listenServerDelegate, new object[] { str });

或:str是GetServerList的参数,如果无参就不写。.Net Core 2.1 中就是因为没有上面的用法,只能采用下面的方法

listenServerDelegate.Invoke(str);

4:
public int GetServerList(string str) { return Int i=1;}

 直接异步操作

无参写法

Action action = () => OpenCameraTcp();
action.BeginInvoke(null, null);

或:有参写法。<string, string>是多个参数各自的类型,<obj1, obj2>是参数对,(info.LatticeNo, info.PackgeNo)是参数值,callback是回调函数

Action<string, string> action = (obj1, obj2) => SG_Warning(info.LatticeNo, info.PackgeNo);
action.BeginInvoke(info.LatticeNo, info.PackgeNo, callback, null);

原文地址:https://www.cnblogs.com/wa502/p/11603462.html