Generics and Events - is there any way to do this?
After all isssues I ran into recently with concurrency of subscribing/ unsubscribing and notifying I tried to put i tall in a generic class and use it.
Alas I fail to find a way since this is not allowed:
public class LCLMulticastEvent<T> where T: System.MulticastDelegate
{
private event T internalEvent;
private object lockObject = new object();
public event T OnEvent
{
add
{
lock( lockObject )
{
internalEvent += value;
}
}
remove
{
lock( lockObject )
{
internalEvent += value;
}
}
}
public void notify( params object[] args)
{
开发者_运维技巧 if( internalEvent != null )
{
lock( lockObject )
{
foreach( T invokee in internalEvent.GetInvocationList() )
{
invokee.DynamicInvoke( args );
}
}
}
}
}
The compiler refuses to accept System.MulticastDelegate
, saying it is a special class...
Is there any way to do it?
Edit: I tried to be too brief in my first exmplanations. What I wanted to to is implement a kind of event-wrapper that is thread-safe. @Thomas: DynamicInvoke should have been the solution...
TIA
Mario
It's not really clear to me what you are trying to achieve here, but maybe this helps: you can make the class generic in the EventArgs
type instead of MultiCastDelegate
public class LCLMulticastEvent<TEventArgs> where TEventArgs : EventArgs
{
private event EventHandler<TEventArgs> internalEvent;
private object lockObject = new object();
public event EventHandler<TEventArgs> OnEvent
{
add { internalEvent += value; }
remove { internalEvent -= value; }
}
}
精彩评论