在我的代码中,我使用BeginInvoke
引发事件,但因为每个事件有不同的EventArgs
,我的代码充满了重复的函数,如:
private void EndAsyncConnect(IAsyncResult iar)
{
var ar = (System.Runtime.Remoting.Messaging.AsyncResult)iar;
var invokedMethod = (EventHandler<InfoArgs>)ar.AsyncDelegate;
invokedMethod.EndInvoke(iar);
}
private void EndAsyncReceived(IAsyncResult iar)
{
var ar = (System.Runtime.Remoting.Messaging.AsyncResult)iar;
var invokedMethod = (EventHandler<ReceivedArgs>)ar.AsyncDelegate;
invokedMethod.EndInvoke(iar);
}
是否有办法使EndAsync函数通用的所有事件?
如果你所有的事件委托类型是EventHandler<T>
,这应该工作:
void CompletionCallback<T>(IAsyncResult iar)
where T : EventArgs
{
var ar = (System.Runtime.Remoting.Messaging.AsyncResult)iar;
var invokedMethod = (EventHandler<T>)ar.AsyncDelegate;
invokedMethod.EndInvoke(iar);
}