I'm trying to come up with a generic way to intercept C# events for processing (e.g. logging, filtering, distributing asynchronously etc.), before passing the event back on to its original consumer.
So to give an example, in the normal flow of things you'd have
class EventProducer
{
public event EventHandler<int> OnEvent;
internal void FireEvent()
{
if (OnEvent != null)
OnEvent(this, 1);
}
}
class EventConsumer
{
public EventConsumer(EventProducer producer)
{
producer.OnEvent += eventHandler;
}
public void eventHandler(object sender, int e)
{
Debug.WriteLine("Consumed " + e);
}
}
In my case, I'd want to insert an additional step between the two.. something like
//event consumer
class EventConsumer
{
//use this to handle one particular event (EventProducer.OnEvent)
InterceptEventHandler<int> EventHandler;
public EventConsumer(EventProducer producer)
{
//just one line of code to insert an event handler to do what I need
//but whoops - cant refer to OnEvent outside of the producer
EventHandler = new InterceptEventHandler<int>(producer.OnEvent, eventHandler);
}
public void eventHandler(object sender, int e)
{
Debug.WriteLine("Consumed " + e);
}
}
//intercepts events, does something with them, then forwards them to original consumer
class InterceptEventHandler<T>
{
public EventHandler<T> Callback;
public InterceptEventHandler(EventHandler<T> eventHook, EventHandler<T> callback)
{
//save callback
Callback = callback;
//subscribe ourselves to the specified event
eventHook += interceptHandler;
}
public void interceptHandler(object sender, T e)
{
//do something with the event here
Debug.WriteLine("Intercepted " + e.ToString());
//then pass callback back to original consumer
Callback(sender, e);
}
}
The problem (as commented above) is that the code doesn't compile because the events themselves are not accessible from outside the producer class. I understand this is because the event handling is implemented as a private class, so can't see any obvious way around this.
Is there any way to intercept and chain events that would allow me to keep the standard event syntax in producer classes?
I realise that I can abandon events, and just use my own equivalent producer/consumer code, but i'll lose the normal benefits of events (e.g. more readable/maintainable, proper syntax highlighting/autocomplete etc.)
EDIT - I also tried fiddling around with the MulticastDelegate class, but while I got the code to compile, I couldn't get the events to be subscribed (effectively OnEvent was always null).
Rather than accepting an EventHandler which is of course not the type of an event, accept an Action<EventHandler> which represents an action that subscribes to the event:
public class InterceptEventHandler
{
public static void Attach<T>(Action<EventHandler<T>> eventHook,
EventHandler<T> callback)
{
eventHook((sender, args) =>
{
doStuffOnFire(sender, args);
callback(sender, args);
});
}
private static void doStuffOnFire<T>(object sender, T e)
{
//...
}
}
You would then call it like so:
public EventConsumer(EventProducer producer)
{
InterceptEventHandler.Attach<int>(
handler => producer.OnEvent += handler,
eventHandler);
}
Related
I want pass event to another event,now I use function to do that.
Can C# pass event like b.WriteEvent += a.WriteEvent ?
If I had a lot class,and just want pass argument to above class.
I want write like : a.event += b.event. b.event += c.event
Instead of a lot no use method.
Thanks.
class Program
{
static void Main(string[] args)
{
ClassA a = new ClassA();
ClassB b = new ClassB();
a.WriteEvent += MainWrite;
b.WriteEvent += a.WireFunction; // Now I use
//b.WriteEvent += a.WriteEvent; <= Can I use like this ?
b.WireFunction("some str");
Console.ReadLine();
}
static void MainWrite(string str)
{
Console.WriteLine(str);
}
}
class ClassA
{
public event Handler WriteEvent;
public void WireFunction(string str)
{
WriteEvent(str);
}
}
class ClassB
{
public event Handler WriteEvent;
public void WireFunction(string str)
{
WriteEvent(str);
}
}
public delegate void Handler(string str);
Fact:You cannot provide an event that subscribes to an event.
All delegates (events, actions or funcs) ar multicast delegates in C#.
That means you can subscribe to an event multiple times.
In order to subscribe to an event you have to provide an action or a function. (I use the term function instead of method because we may provide a lambda)
What follows is snipped that subscribes all subscribers of Event1 to Event2.
I believe this is what you intend to do.
public class SomeClass
{
public event EventHandler Event1;
public event EventHandler Event2;
public SomeClass()
{
Event1 += Subscriber1;
Event1 += Subscriber2;
var subscribers = Event1.GetInvocationList();
if(subscribers != null)
{
foreach(var subscriber in subscribers)
{
EventHandler realSubscriber = (EventHandler)subscriber;
Event2 += realSubscriber;
}
}
Event1(this, EventArgs.Empty);
Event2(this, EventArgs.Empty);
}
public void Subscriber1(object sender, EventArgs e)
{
Console.WriteLine("Subscriber 1 invoked");
}
public void Subscriber2(object sender, EventArgs e)
{
Console.WriteLine("Subscriber 2 invoked");
}
}
Creating an instance of the SomeClass will print:
Subscriber 1 invoked
Subscriber 2 invoked
Subscriber 1 invoked
Subscriber 2 invoked
EDIT:
I tried to move the logic to an extension method and also to a normal utility method. Both did not work very well because events are null when they have no subscribers. Passing an event without subscribers would then result in the same behaviour as if null was passed. For now, this is the best I could come up with.
I have a class that will write a log. The class needs to raise an event (under specific circumstances not indicated below), that will be comsumed by a class to react on it. I have the code below but as soon as I try to raise the event, I get an error on the line as indicated, that
Object reference not set to an instance of an object
Any idea what I'm missing?
//1. Class where event is registered
public class LogEvent
{
public delegate void WriteLogEventHandler(object Sender, WriteLogEventArgs e);
public event WriteLogEventHandler WriteLog;
public class WriteLogEventArgs : EventArgs
{
public string Message { get; set; }
public WriteLogEventArgs(string message) : base()
{
Message = message;
}
}
//Raise the event.
internal void OnWriteLog(WriteLogEventArgs e)
{
WriteLog(this, e); //Error here. Seems like WriteLog is null
}
//2. Class where event is raised.
public class Logs
{
public static void WriteLog(string message)
{
LogEvent.WriteLogEventArgs args = new LogEvent.WriteLogEventArgs(message);
new LogEvent().OnWriteLog(args);
}
}
//3. Class where event should be consumed
public class MyClass()
{
private LogEvent _logEvent;
public MyClass()
{
//Subscribe to event:
_logEvent = new LogEvent();
_logEvent.WriteLog += (sender, args) => { DoSomething(args.Message); };
}
public void DoSomething(string message)
{ ... }
}
Two issues:
You're raising the event whether or not anyone has subscribed to it. Don't do that - you will get a NullReferenceException if you call WriteLog(this, e) when WriteLog is null. In C# 6 it's easy to avoid this:
WriteLog?.Invoke(this, e);
You're subscribing to the event on a different LogEvent instance than the one which is raising the event. This is more of a design issue than anything else - it makes no sense for an individual log event to have a list of subscribers. Instead, you should have a Logger or similar which has the subscribers (via an event), then each LogEvent is passed to those subscribers. You'd create one Logger, subscribe to it, then call WriteLog on the same instance.
How should I fix SonarLint Rule S1172 "Unused method parameters should be removed" when I create EventHandler methods.
public void Subscribe()
{
MyEvent += OnMyEvent;
}
public void UnSubscribe()
{
MyEvent -= OnMyEvent;
}
private void OnMyEvent(object sender, EventArgs e)
{
DoSomething();
}
You could rewrite the code with Reactive Extensions and making 'Observables' but that is quite complex solution for simple event handlers. Another option could be to rewrite the code like:
public void Subscribe()
{
MyEvent += (s,e) => DoSomething();
}
But the question then is how do you do the UnSubscribe()? By my opinion the unused parameters is not applicable to event handler methods. But it might be difficult to make detection for that in SonarLint.
If you need to unsubscribe, you'll need to store the delegate (remove static for proper code, this is pasted from a hacked console app project):
public static event EventHandler TestEvent;
private static EventHandler saved = (s, e) => DoSomething();
static void Main(string[] args)
{
TestEvent += saved;
TestEvent -= saved;
}
internal static void DoSomething()
{
}
Or use a mass-unsubscribe:
foreach (Delegate d in TestEvent.GetInvocationList())
{
TestEvent -= (EventHandler)d;
}
Or if you own the event, you could also use this to unsubscribe all:
TestEvent = null;
Or just use the syntax you've always used and create a non-anonymous method, like you show above. There's nothing wrong with that syntax. You could do the obligatory
if (sender == null)
throw ArgumentNullException(nameof(sender));
to get rid of the warning ;)
I'm trying to find the best way to create a system where event sources can be added to a manager class, which will then re-dispatch their events to listeners. Specifically, I have many different input sources (keyboard input source, mouse input source, virtual keyboard input source, etc) and I'd like to allow developers to listen for, say, the KeyDown event on both the keyboard input source and the input manager itself (to catch this event from any active input source).
It's easy to brute-force a solution where I end up creating many "dispatch" functions, that simply re-dispatch events when they come through, but I end up having dozens of single line functions and I have to create new functions whenever a new event is added to an input source interface.
I've considered using lambdas, but I need a way to unhook the events if an input source is removed from the manager. I can keep the lambda in a dictionary, keyed by input source, but many of the events have different arg classes, and creating multiple dictionaries to do this starts to get ugly.
I'm wondering if I'm missing some simple way of doing this which keeps things clean and keeps the amount of additional code I need to write down.
For reference, here's a sample of the objects I'm working with:
public interface IInputSource {}
public interface IKeyboardInputSource : IInputSource
{
event EventHandler<KeyboardEventArgs> KeyDown;
event EventHandler<KeyboardEventArgs> KeyUp;
}
public interface IMouseInputSource : IInputSource
{
event EventHandler<MouseEventArgs> MouseDown;
event EventHandler<MouseEventArgs> MouseUp;
}
public class InputManager : IKeyboardInputSource, IMouseInputSource
{
private List<IInputSource> InputSources;
//Event declarations from IKeyboardInputSource and IMouseInputSource
public void AddSource(IInputSource source)
{
InputSources.Add(source);
if (source is IKeyboardInputSource)
{
var keyboardSource = source as IKeyboardInputSource;
keyboardSource.KeyDown += SendKeyDown;
// Listen for other keyboard events...
}
if (source is IMouseInputSource)
{
// Listen for mouse events...
}
}
public void RemoveSource(IInputSource source)
{
if (source is IKeyboardInputSource)
{
var keyboardSource = source as IKeyboardInputSource;
keyboardSource.KeyDown -= SendKeyDown;
// Remove other keyboard events...
}
if (source is IMouseInputSource)
{
// Remove mouse events...
}
InputSources.Remove(source);
}
private void SendKeyDown(object sender, KeyboardEventArgs e)
{
if (KeyDown != null)
KeyDown(sender, e);
}
//Other "send" functions
}
Have you looked at the Reactive Extensions (Rx) framework? Looks like it will what you are asking for and gives you a rich functional/lambda like api to manage and process events.
The Reactive Extensions (Rx) is a library for composing asynchronous and event-based programs using observable sequences and LINQ-style query operators
Probably something like this would help - it's a generic approach, with both direct event subscription or via 'sink' interface
interface IInputSource<T> where T : EventArgs
{
event EventHandler<T> InputEvent;
}
interface IInputSink<in T> where T : EventArgs
{
void InputMessageHandler(object sender, T eventArgs);
}
internal class InputManager
{
private Dictionary<Type, object> _inputSources;
private Dictionary<Type, object> _inputSinks;
private Dictionary<Type, object> _events;
public void AddSource<T>(IInputSource<T> source) where T : EventArgs
{
_inputSources[typeof(T)] = _inputSources; //add source
_events[typeof(T)] = (EventHandler<T>)Dispatch; //register event for subscribers
source.InputEvent += Dispatch;
source.InputEvent += Dispatch2;
}
// Dispatch trough direct event subscriptions;
private void Dispatch<T>(object sender, T e) where T : EventArgs
{
var handler = _events[typeof(T)] as EventHandler<T>;
handler.Invoke(sender, e);
}
// Dispatch trough IInputSink subscriptions;
private void Dispatch2<T>(object sender, T e) where T : EventArgs
{
var sink = _inputSinks[typeof(T)] as IInputSink<T>;
sink.InputMessageHandler(sender, e);
}
//Subscription: Client should provide handler into Subscribe()
//or subscribe with IInputSink<MyEvent> implementation (Subscribe2())
public void Subscribe<T>(EventHandler<T> handler) where T : EventArgs
{
var #event = _events[typeof(T)] as EventHandler<T>;
_events[typeof(T)] = #event + handler;
}
public void Subscribe2<T>(IInputSink<T> sink) where T : EventArgs
{
_inputSinks[typeof(T)] = sink;
}
}
class XXXX : EventArgs
{
}
public class Sink: IInputSink<XXXX>
{
#region Implementation of IInputSink<in XXXX>
public void InputMessageHandler(object sender, XXXX eventArgs)
{
throw new NotImplementedException();
}
#endregion
public Sink()
{
var v = new InputManager();
v.Subscribe<XXXX>(GetInputEvent);
v.Subscribe2(this);
}
private void GetInputEvent(object sender, XXXX xxxx)
{
throw new NotImplementedException();
}
}
I am currently having a hardtime understanding and implementing events in C# using delagates. I am used to the Java way of doing things:
Define an interface for a listener type which would contain a number of method definitions
Define adapter class for that interface to make things easier if I'm not interested in all the events defined in a listener
Define Add, Remove and Get[] methods in the class which raises the events
Define protected fire methods to do the dirty work of looping through the list of added listeners and calling the correct method
This I understand (and like!) - I know I could do this exactly the same in c#, but it seems that a new (better?) system is in place for c#. After reading countless tutorials explaining the use of delegates and events in c# I still am no closer to really understanding what is going on :S
In short, for the following methods how would I implement the event system in c#:
void computerStarted(Computer computer);
void computerStopped(Computer computer);
void computerReset(Computer computer);
void computerError(Computer computer, Exception error);
^ The above methods are taken from a Java application I once made which I'm trying to port over to c#.
Many many thanks!
You'd create four events, and methods to raise them, along with a new EventArgs-based class to indicate the error:
public class ExceptionEventArgs : EventArgs
{
private readonly Exception error;
public ExceptionEventArgs(Exception error)
{
this.error = error;
}
public Error
{
get { return error; }
}
}
public class Computer
{
public event EventHandler Started = delegate{};
public event EventHandler Stopped = delegate{};
public event EventHandler Reset = delegate{};
public event EventHandler<ExceptionEventArgs> Error = delegate{};
protected void OnStarted()
{
Started(this, EventArgs.Empty);
}
protected void OnStopped()
{
Stopped(this, EventArgs.Empty);
}
protected void OnReset()
{
Reset(this, EventArgs.Empty);
}
protected void OnError(Exception e)
{
Error(this, new ExceptionEventArgs(e));
}
}
Classes would then subscribe to the event using either a method or a an anonymous function:
someComputer.Started += StartEventHandler; // A method
someComputer.Stopped += delegate(object o, EventArgs e)
{
Console.WriteLine("{0} has started", o);
};
someComputer.Reset += (o, e) => Console.WriteLine("{0} has been reset");
A few things to note about the above:
The OnXXX methods are protected so that derived classes can raise the events. This isn't always necessary - do it as you see fit.
The delegate{} piece on each event declaration is just a trick to avoid having to do a null check. It's subscribing a no-op event handler to each event
The event declarations are field-like events. What's actually being created is both a variable and an event. Inside the class you see the variable; outside the class you see the event.
See my events/delegates article for much more detail on events.
You'll have to define a single delegate for that
public delegate void ComputerEvent(object sender, ComputerEventArgs e);
ComputerEventArgs would be defined like this:
public class ComputerEventArgs : EventArgs
{
// TODO wrap in properties
public Computer computer;
public Exception error;
public ComputerEventArgs(Computer aComputer, Exception anError)
{
computer = aComputer;
error = anError;
}
public ComputerEventArgs(Computer aComputer) : this(aComputer, null)
{
}
}
The class that fires the events would have these:
public YourClass
{
...
public event ComputerEvent ComputerStarted;
public event ComputerEvent ComputerStopped;
public event ComputerEvent ComputerReset;
public event ComputerEvent ComputerError;
...
}
This is how you assign handlers to the events:
YourClass obj = new YourClass();
obj.ComputerStarted += new ComputerEvent(your_computer_started_handler);
Your handler is:
private void ComputerStartedEventHandler(object sender, ComputerEventArgs e)
{
// do your thing.
}
The main difference is that in C# the events are not interface-based. Instead, the event publisher declares the delegate which you can think of as a function pointer (although not exactly the same :-)). The subscriber then implements the event prototype as a regular method and adds a new instance of the delegate to the event handler chain of the publisher. Read more about delegates and events.
You can also read short comparison of C# vs. Java events here.
First of all, there is a standard method signature in .Net that is typically used for events. The languages allow any sort of method signature at all to be used for events, and there are some experts who believe the convention is flawed (I mostly agree), but it is what it is and I will follow it for this example.
Create a class that will contain the event’s parameters (derived from EventArgs).
public class ComputerEventArgs : EventArgs
{
Computer computer;
// constructor, properties, etc.
}
Create a public event on the class that is to fire the event.
class ComputerEventGenerator // I picked a terrible name BTW.
{
public event EventHandler<ComputerEventArgs> ComputerStarted;
public event EventHandler<ComputerEventArgs> ComputerStopped;
public event EventHandler<ComputerEventArgs> ComputerReset;
...
}
Call the events.
class ComputerEventGenerator
{
...
private void OnComputerStarted(Computer computer)
{
EventHandler<ComputerEventArgs> temp = ComputerStarted;
if (temp != null) temp(this, new ComputerEventArgs(computer)); // replace "this" with null if the event is static
}
}
Attach a handler for the event.
void OnLoad()
{
ComputerEventGenerator computerEventGenerator = new ComputerEventGenerator();
computerEventGenerator.ComputerStarted += new EventHandler<ComputerEventArgs>(ComputerEventGenerator_ComputerStarted);
}
Create the handler you just attached (mostly by pressing the Tab key in VS).
private void ComputerEventGenerator_ComputerStarted(object sender, ComputerEventArgs args)
{
if (args.Computer.Name == "HAL9000")
ShutItDownNow(args.Computer);
}
Don't forget to detach the handler when you're done. (Forgetting to do this is the biggest source of memory leaks in C#!)
void OnClose()
{
ComputerEventGenerator.ComputerStarted -= ComputerEventGenerator_ComputerStarted;
}
And that's it!
EDIT: I honestly can't figure out why my numbered points all appear as "1." I hate computers.
there are several ways to do what you want. The most direct way would be to define delegates for each event in the hosting class, e.g.
public delegate void ComputerStartedDelegate(Computer computer);
protected event ComputerStartedDelegate ComputerStarted;
public void OnComputerStarted(Computer computer)
{
if (ComputerStarted != null)
{
ComputerStarted.Invoke(computer);
}
}
protected void someMethod()
{
//...
computer.Started = true; //or whatever
OnComputerStarted(computer);
//...
}
any object may 'listen' for this event simply by:
Computer comp = new Computer();
comp.ComputerStarted += new ComputerStartedDelegate(
this.ComputerStartedHandler);
protected void ComputerStartedHandler(Computer computer)
{
//do something
}
The 'recommended standard way' of doing this would be to define a subclass of EventArgs to hold the Computer (and old/new state and exception) value(s), reducing 4 delegates to one. In this case that would be a cleaner solution, esp. with an Enum for the computer states in case of later expansion. But the basic technique remains the same:
the delegate defines the signature/interface for the event handler/listener
the event data member is a list of 'listeners'
listeners are removed using the -= syntax instead of +=
In c# events are delegates. They behave in a similar way to a function pointer in C/C++ but are actual classes derived from System.Delegate.
In this case, create a custom EventArgs class to pass the Computer object.
public class ComputerEventArgs : EventArgs
{
private Computer _computer;
public ComputerEventArgs(Computer computer) {
_computer = computer;
}
public Computer Computer { get { return _computer; } }
}
Then expose the events from the producer:
public class ComputerEventProducer
{
public event EventHandler<ComputerEventArgs> Started;
public event EventHandler<ComputerEventArgs> Stopped;
public event EventHandler<ComputerEventArgs> Reset;
public event EventHandler<ComputerEventArgs> Error;
/*
// Invokes the Started event */
private void OnStarted(Computer computer) {
if( Started != null ) {
Started(this, new ComputerEventArgs(computer));
}
}
// Add OnStopped, OnReset and OnError
}
The consumer of the events then binds a handler function to each event on the consumer.
public class ComputerEventConsumer
{
public void ComputerEventConsumer(ComputerEventProducer producer) {
producer.Started += new EventHandler<ComputerEventArgs>(ComputerStarted);
// Add other event handlers
}
private void ComputerStarted(object sender, ComputerEventArgs e) {
}
}
When the ComputerEventProducer calls OnStarted the Started event is invoked which in turn will call the ComputerEventConsumer.ComputerStarted method.
The delegate declares a function signature, and when it's used as an event on a class it also acts as a collection of enlisted call targets. The += and -= syntax on an event is used to adding a target to the list.
Given the following delegates used as events:
// arguments for events
public class ComputerEventArgs : EventArgs
{
public Computer Computer { get; set; }
}
public class ComputerErrorEventArgs : ComputerEventArgs
{
public Exception Error { get; set; }
}
// delegates for events
public delegate void ComputerEventHandler(object sender, ComputerEventArgs e);
public delegate void ComputerErrorEventHandler(object sender, ComputerErrorEventArgs e);
// component that raises events
public class Thing
{
public event ComputerEventHandler Started;
public event ComputerEventHandler Stopped;
public event ComputerEventHandler Reset;
public event ComputerErrorEventHandler Error;
}
You would subscribe to those events with the following:
class Program
{
static void Main(string[] args)
{
var thing = new Thing();
thing.Started += thing_Started;
}
static void thing_Started(object sender, ComputerEventArgs e)
{
throw new NotImplementedException();
}
}
Although the arguments could be anything, the object sender and EventArgs e is a convention that's used very consistently. The += thing_started will first create an instance of the delegate pointing to target method, then add it to the event.
On the component itself you would typically add methods to fire the events:
public class Thing
{
public event ComputerEventHandler Started;
public void OnStarted(Computer computer)
{
if (Started != null)
Started(this, new ComputerEventArgs {Computer = computer});
}
}
You must test for null in case no delegates have been added to the event. When you make the method call however all delegates which have been added will be called. This is why for events the return type is void - there is no single return value - so to feed back information you would have properties on the EventArgs which the event handlers would alter.
Another refinement would be to use the generic EventHandler delegate rather than declaring a concrete delegate for each type of args.
public class Thing
{
public event EventHandler<ComputerEventArgs> Started;
public event EventHandler<ComputerEventArgs> Stopped;
public event EventHandler<ComputerEventArgs> Reset;
public event EventHandler<ComputerErrorEventArgs> Error;
}
Thank you all so much for your answers! Finally I'm starting to understand what is going on. Just one thing; It seems that if each event had a different number/type of arguments I'd need to create a different :: EventArgs class to deal with it:
public void computerStarted(Computer computer);
public void computerStopped(Computer computer);
public void computerReset(Computer computer);
public void breakPointHit(Computer computer, int breakpoint);
public void computerError(Computer computer, Exception exception);
This would require three classses to deal with the events!? (Well two custom, and one using the default EventArgs.Empty class)
Cheers!
Ok, FINAL clarification!: So this is pretty much the best I can do code-wise to implement those events?
public class Computer {
public event EventHandler Started;
public event EventHandler Stopped;
public event EventHandler Reset;
public event EventHandler<BreakPointEvent> BreakPointHit;
public event EventHandler<ExceptionEvent> Error;
public Computer() {
Started = delegate { };
Stopped = delegate { };
Reset = delegate { };
BreakPointHit = delegate { };
Error = delegate { };
}
protected void OnStarted() {
Started(this, EventArgs.Empty);
}
protected void OnStopped() {
Stopped(this, EventArgs.Empty);
}
protected void OnReset() {
Reset(this, EventArgs.Empty);
}
protected void OnBreakPointHit(int breakPoint) {
BreakPointHit(this, new BreakPointEvent(breakPoint));
}
protected void OnError(System.Exception exception) {
Error(this, new ExceptionEvent(exception));
}
}
}