第一种:private delegate void OnReceivedData(byte[] data);
在方法中调用this.Invoke(new OnReceivedData(ProcessReceivedData), data);
执行方法 private void ProcessReceivedData(byte[] data)
{...}
第二种:
委托的BeginInvoke中的callback怎样向她传递参数
-
class Program { static void Main(string[] args) { AsyncTest test = new AsyncTest(); // 这就是你需要传的参数,注意后面的2000是怎么传进去的,,(参数类型是Object,只是在这里我传了int类型) SalaryEventHandler dele = test.YearlySalary;//使用参数初始化一个对象 dele.BeginInvoke(100000, 15, 100000, GetResultCallBack, 2000); //用初始化的对象启动方法 Console.ReadLine(); } static void GetResultCallBack(IAsyncResult asyncResult) { //获取获取参数 AsyncResult result = (AsyncResult)asyncResult; SalaryEventHandler salDel = (SalaryEventHandler)result.AsyncDelegate; //调用EndInvoke获取返回值 object val = salDel.EndInvoke(asyncResult); //int para = (int)asyncResult.AsyncState; //Console.WriteLine(para); //输出:2000 } } //认真吃透上面的每句代码, 你得问题就解决了
第三种:
public class StateObject
{
public string AssociatedID = string.Empty;
public byte[] Buffer = new byte[0x1000];
public const int BufferSize = 0x1000;
public Socket WorkSocket;
}
StateObject state = new StateObject();
state.WorkSocket = socket;
socket.BeginReceive(state.Buffer, 0, 0x1000, SocketFlags.None, new AsyncCallback(this.ReceiveCallback), state);
private void ReceiveCallback(IAsyncResult ar)
{
StateObject asyncState = (StateObject) ar.AsyncState;
try
{
int num = asyncState.WorkSocket.EndReceive(ar);
if (num > 0)
{
。。。 = asyncState.Buffer;
。。。asyncState.WorkSocket
}
else
{
}
}
catch (Exception exception)
{
}
}