Implementing a custom event handler from interface [duplicate] - c#

This question already has answers here:
C# Language Design: explicit interface implementation of an event
(4 answers)
Closed 5 years ago.
I am in the process of creating a system that can receive messages from a variety of different sources.
Using the interface approach, I am adding a custom event which will pass the message back to the calling application.
I've used Vistual Studio's "scaffolding" using Ctrl-. to provide the implementation for the concrete class, but its added the add and remove elements but I dont really know how to wire that bit up.
Interface class
public class MessageEventArgs : EventArgs
{
public Message { get; set; }
}
public interface MessageBroker
{
void Start();
event EventHandler<MessageEventArgs> OnMessageReceived;
}
Implementation class
public class MessageSourceA : MessageBroker
{
event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
add
{
// What goes here
}
remove
{
// What goes here
}
}
void MessageBroker.Start()
{
}
}
Main Program
static void Main(string[] args)
{
MessageBroker sourceA = new MessageSourceA ();
sourceA.OnMessageReceived += sourceA_OnMessageReceived;
}
private static void sourceA_OnMessageReceived(object sender, MessageEventArgs e)
{
// Do stuff with message
}
Thanks...

You could normally implement from interface.
public class MessageSourceA : IMessageBroker
{
public void Start();
public event EventHandler<MessageEventArgs> OnMessageReceived;
}
I suggest you to rename MessageBroker to IMessageBroker as its a naming convention. Since "I" helps to differentiate between class and interface when looking at code.
If there is proper reason to implement interface explicitly you need private event handler.
private event EventHandler<MessageEventArgs> _onMessageReceived;
event EventHandler<MessageEventArgs> MessageBroker.OnMessageReceived
{
add
{
_onMessageRecieved += value;
}
remove
{
_onMessageRecieved -= value;
}
}

Related

C# : raise event in class bases on event in other class

In my application I have a interface IEncoder that is having event EncoderCaller.
public interface IEncoder
{
event EncoderCaller EncoderCalled;
}
public delegate void EncoderCaller(object Source, EventArgs args);
public class Video
{
public string Title { get; set; }
}
public class VideoEventArgs : EventArgs
{
public Video xVideo { get; set; }
}
public class DetectionAction : IEncoder
{
public event EncoderCaller EncoderCalled;
public void Encode(Video video)
{
//some logic to encode video
OnVideoEncoded();
}
protected virtual void OnVideoEncoded()
{
if (EncoderCalled != null)
EncoderCalled(this, EventArgs.Empty);
}
}
public class Client1: IEncoder
{
}
I need some mechanism by which I should be able to share a contract, if that is implemented by any client then that event will trigger event in my class DetectionAction .
Can someone tell me, Am I doing right thing.
How it can be done?
If you have two classes in the same process, you could consider explicitly chain events like this:
public class Client1 : IEncoder
{
public event EncoderCaller EncoderCalled;
public Client1(IEncoder anotherEncoder)
{
// Listen to event raised on another instance and raise event on this instance.
anotherEncoder.EncoderCalled += OnAnotherEncoderCalled;
}
private void OnAnotherEncoderCalled(object source, EventArgs args)
{
if (EncoderCalled != null)
EncoderCalled(this, EventArgs.Empty);
}
}
In this case, for example, anotherEncoder is DetectionAction.
However, if you are seeking solution for sharing events between two different applications running in different processes, you might be looking at inter-process communication, like this post:
Listen for events in another application
And the above example code still works, but the IEncoder in this case is an implementation with IPC support, for example a message queue listener which raises the event on message received.

Using Weak Event in .NetCore

It looks like the Weak Events or more specifically WeakEventManager or IWeakEventListener are not available in .Net Core as they are part of WindowsBase assembly.
Are there an alternatives to this feature?
Events are often a source of memory leaks in applications and weak references are a great way of dealing with this issue.
I couldn't find any information on this topic in stackoverflow
The library Nito.Mvvm.Core has a WeakCanExecuteChagned class that does weak events using the command class you could use as a starting point for writing your manager backed by a WeakCollection<EventHandler>.
Here is a simple example using a custom class with a event named Foo that takes in a FooEventArgs object.
public class MyClass
{
private readonly WeakCollection<EventHandler<FooEventArgs>> _foo = new WeakCollection<EventHandler<FooEventArgs>>();
public event EventHandler<FooEventArgs> Foo
{
add
{
lock (_foo)
{
_foo.Add(value);
}
}
remove
{
lock (_foo)
{
_foo.Remove(value);
}
}
}
protected virtual void OnFoo(FooEventArgs args)
{
lock (_foo)
{
foreach (var foo in _foo.GetLiveItems())
{
foo(this, args);
}
}
}
}
My library System.Waf.Core provides a WeakEvent implementation that can be used as an alternative to the WeakEventManager.
Example for INotifyPropertyChanged.PropertyChanged:
public class Publisher : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
}
public class Subscriber
{
public void Init(Publisher publisher)
{
// Instead of publisher.PropertyChanged += Handler; use the following statement:
WeakEvent.PropertyChanged.Add(publisher, Handler)
}
public void Handler(object? sender, PropertyChangedEventArgs e) { }
}
More details can be found on this Wiki page Weak Event.

Observer pattern in C# / how to make a Form an observer

I fail to find an answer so far, probably just lacking the appropriate keywords to search for.
I want to implement an Observer Pattern in C#, so any Observer object can subscribe to a Subject object and then receives all its notifications. Then it decides based on the Notification type whether it's important or not.
public class Subject
{
private List<Observer> observers;
public void AttachObserver(Observer Observer)
{
this.observers.Add(Observer);
}
public void DetachObserver(Observer Observer)
{
this.observers.Remove(Observer);
}
public void NotifyObservers(CommonNotification Notification) // who we are, what kind of notification, bla bla
{
foreach(Observer Observer in observers)
{
Observer.OnNotify(Notification);
}
}
}
public class Observer
{
public abstract void OnNotify(CommonNotification Notification);
}
So any object wanting to subscribe to a Subject needs to be an inheritance of the Observer class. But how to do that? My MainForm is based on Form. If I replace the Observer class with a general object it won't implement an OnNotify() event.
What's the point I am missing here? I know I should properly implement it using Event handlers but in order to learn how basic design patterns work I rather implement things myself first.
Short Answer: look at first answer to this question: Super-simple example of C# observer/observable with delegates
I understand you wanting to try and implement it yourself but delegates and events are really the natural fit here (and are in fact an implemention of the observer pattern built into c#).
If still want to do it yourself I would recommend using interfaces instead of abstract/concrete classes.
public interface ISubject
{
void AttachObserver(IObserver observer);
void DetachObserver(IObserver observer);
void NotifyObservers(CommonNotification Notification);
}
public interface IObserver
{
void OnNotify(CommonNotification Notification);
}
Your form could then implement IObserver (or ISubject or both!!).
public class MyForm : Form, IObserver
{
...
}
you can use Interface instead of abstract class like this
public Interface IObserver
{
public void OnNotify(CommonNotification Notification);
}
....
public class MyForm:Form, IObserver {
....
}
You should replace your Observer class with an Interface:
public Interface IObserver
{
public void OnNotify(CommonNotification Notification);
}
Then your mainform (or anything else) can implement IObserver
You can implement it very easily using event. I am giving a sample code -
public class MyForm : Form
{
public event Action btn1Clicked;
private void button1_Click(object sender, EventArgs e)
{
btn1Clicked();
}
}
public abstract class AbsObserver
{
protected MyForm Form;
public AbsObserver(Subject subject)
{
subject.Attach(OnNotify);
Form = new MyForm();
Form.btn1Clicked += Form_btn1Clicked;
}
void Form_btn1Clicked()
{
Console.WriteLine("Do button click task");
}
public abstract void OnNotify();
}
public class Observer1 : AbsObserver
{
public Observer1(Subject subject)
: base(subject)
{
}
public override void OnNotify()
{
Console.WriteLine("observer1 notified");
}
}
public class Observer2 : AbsObserver
{
public Observer2(Subject subject)
: base(subject)
{
}
public override void OnNotify()
{
Console.WriteLine("observer2 notified");
}
}
public class Subject
{
private event Action Notify;
public void Attach(Action a)
{
Notify += a;
}
private void NotifyAll()
{
Notify();
}
}
Here forms are not observers. The observers have the object of form and all form related issues are handled by the observers. This is kind of composting.

Delegates and Events with multiple classes

This has taken me quite a few days to develop a demo of communicating between classes with delegates and events. I would like to know if this is the best practices way of accomplishing this passing of data between classes or not. If there is a better method please let me know. Specifically, if something happens in a subclass how do you get it back to the main class. This would be particularly useful when doing n-tier architecture by separating out the User Interface from the Business Logic Level, and the Data Access Level.
I have a form that has 3 text boxes: tb1, tb2, and tbAnswer.
I also have a button that says "Add" and it is just button1.
The main form is:
namespace DelegateTest
{
public delegate void ShowMessage(object sender, Form1.AnswerEventArgs e);
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void a_OnShowMessage(object sender, AnswerEventArgs e)
{
tbAnswer.Text = e.answer;
}
public class AnswerEventArgs :EventArgs
{
public string answer { get; set; }
}
private void button1_Click(object sender, EventArgs e)
{
AddClass a = new AddClass();
a.OnShowMessage += new ShowMessage(a_OnShowMessage);
a.AddMe(Convert.ToInt16(tb1.Text), Convert.ToInt16(tb2.Text));
}
}
}
and the subform called AddClass.cs is:
namespace DelegateTest
{
class AddClass
{
public event ShowMessage OnShowMessage;
public void AddMe(int a, int b)
{
Form1.AnswerEventArgs e = new Form1.AnswerEventArgs();
e.answer = (a+b).ToString();
OnShowMessage(this, e);
}
}
}
Your approach is sound except for two details.
First, a NullPointerException will occur if your event is raised before any handlers are added. You can get around this in one of two ways.
1) Make a local copy (to avoid race condition) and check it for null:
var showMessage = OnShowMessage;
if (showMessage != null)
{
showMessage(this, e);
}
2) Initialize your event to an empty delegate:
public event ShowMessage OnShowMessage = delegate { };
Second, you do not need to declare your own delegate in this case. You can simply create a standard EventHandler with your own event args:
public event EventHandler<Form1.AnswerEventArgs> OnShowMessage = delegate { };
See How to: Publish Events that Conform to .NET Framework Guidelines for more information.

Why events can't be used in the same way in derived classes as in the base class in C#?

In following code, I want to extend the behaviour of a class by deriving/subclassing it, and make use of an event of the base class:
public class A
{
public event EventHandler SomeEvent;
public void someMethod()
{
if(SomeEvent != null) SomeEvent(this, someArgs);
}
}
public class B : A
{
public void someOtherMethod()
{
if(SomeEvent != null) SomeEvent(this, someArgs); // << why is this not possible?
//Error: The event 'SomeEvent' can only appear on the left hand side of += or -=
//(except when used from within the type 'A')
}
}
Why isn't it possible?
And what is the common solution for this kind of situation?
Others have explained how to get round the issue, but not why it's coming up.
When you declare a public field-like event, the compiler creates a public event, and a private field. Within the same class (or nested classes) you can get at the field directly, e.g. to invoke all the handlers. From other classes, you only see the event, which only allows subscription and unsubscription.
The standard practice here is to have a protected virtual method OnSomeEvent on your base class, then call that method in derived classes. Also, for threading reasons you will want to keep a reference to the handler before checking null and calling it.
For an explanation of the why read Jon Skeet's answer or the C# specification which describes how the compiler automatically creates a private field.
Here is one possible work around.
public class A
{
public event EventHandler SomeEvent;
public void someMethod()
{
OnSomeEvent();
}
protected void OnSomeEvent()
{
EventHandler handler = SomeEvent;
if(handler != null)
handler(this, someArgs);
}
}
public class B : A
{
public void someOtherMethod()
{
OnSomeEvent();
}
}
Edit: Updated code based upon Framework Design Guidelines section 5.4 and reminders by others.
Todd's answer is correct. Often you will see this implemented throughout the .NET framework as OnXXX(EventArgs) methods:
public class Foo
{
public event EventHandler Click;
protected virtual void OnClick(EventArgs e)
{
var click = Click;
if (click != null)
click(this, e);
}
}
I strongly encourage you to consider the EventArgs<T>/EventHandler<T> pattern before you find yourself making all manner of CustomEventArgs/CustomEventHandler for raising events.
The reason the original code doesn't work is because you need to have access to the event's delegate in order to raise it, and C# keeps this delegate private.
Events in C# are represented publicly by a pair of methods, add_SomeEvent and remove_SomeEvent, which is why you can subscribe to an event from outside the class, but not raise it.
My answer would be that you shouldn't have to do this.
C# nicely enforces Only the type declaring/publishing the event should fire/raise it.
If the base class trusted derivations to have the capability to raise its events, the creator would expose protected methods to do that. If they don't exist, its a good hint that you probably shouldn't do this.
My contrived example as to how different the world would be if derived types were allowed to raise events in their ancestors. Note: this is not valid C# code.. (yet..)
public class GoodVigilante
{
public event EventHandler LaunchMissiles;
public void Evaluate()
{
Action a = DetermineCourseOfAction(); // method that evaluates every possible
// non-violent solution before resorting to 'Unleashing the fury'
if (null != a)
{ a.Do(); }
else
{ if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty); }
}
virtual protected string WhatsTheTime()
{ return DateTime.Now.ToString(); }
....
}
public class TriggerHappy : GoodVigilante
{
protected override string WhatsTheTime()
{
if (null != LaunchMissiles) LaunchMissiles(this, EventArgs.Empty);
}
}
// client code
GoodVigilante a = new GoodVigilante();
a.LaunchMissiles += new EventHandler(FireAway);
GoodVigilante b = new TriggerHappy(); // rogue/imposter
b.LaunchMissiles += new EventHandler(FireAway);
private void FireAway(object sender, EventArgs e)
{
// nuke 'em
}
Wrap it with a protected virtual On... method:
public class BaseClass
{
public event EventHandler<MyArgs> SomeEvent;
protected virtual void OnSomeEvent()
{
if(SomeEvent!= null)
SomeEvent(this, new MyArgs(...) );
}
}
Then override this in a derived class
public class DerivedClass : BaseClass
{
protected override void OnSomeEvent()
{
//do something
base.OnSomeEvent();
}
}
You'll set this pattern all over .Net - all form and web controls follow it.
Do not use the prefix Raise... - this is not consistent with MS's standards and can cause confusion elsewhere.

Categories

Resources