my Problem are the events from the WCF client. I hand the client object to some classes. And in this classes i created the events. If i created in different classes the same event it's fires many times. I want that only the event fires in the class where i call the WCF.
How can i solve the Problem? Only Remove each event after complete?
Sry for my english ;)
Thanks....
Hi
I don't understand your question quite well, but I'll try to answer the way I did.
When you reference a WCF service, as you know proxy classes will be generated in client project. This proxy classes share the same data member's Interface which is on the server-side, but not the behavior. So for instance, all properties will be accessible from the client, but not events, methods and so on. Maybe you can write what you are trying to accomplish and we may help?
Update
Ok, now I think I understand. Well that's a solution to remove each event which shouldn't fire before you execute AddNumber method. Another solution is to keep track of calling classes. for example
public static ArrayList eventObjects = new ArrayList(); //Declare a global array list which will be accessible from all classes
eventObjects.Add(this); //Before calling AddNumber method
_client.AddNumber += new EventHandler<AddNumberCompletedEventArgs>(_client_AddNumberCompleted);
void _client_AddNumberCompleted(object sender, AddNumberCompletedEventArgs e)
{
if(ar.Contains(this))
{
//Do what you want to do here. Other classes will receive this event too, but they will not react.
eventObjects.Remove(this);
}
}
However I must warn you that this is not a best approach. I can't suggest you a better way because I don't know what you are trying to accomplish.
okay sorry.
I added the WCF to the Service References in the client project.
Then i created a instance from the Webservice Client:
private WServiceClient _client = new WService.WServiceClient();
I hand this object to several classes. In this classes i create the complete events from some Methodes from the WCF (asyc calls). Like this:
_client.AddNumber += new EventHandler<AddNumberCompletedEventArgs>(_client_AddNumberCompleted);
void _client_AddNumberCompleted(object sender, AddNumberCompletedEventArgs e)
{
}
The problem is that i use some methods multiple in different classes, i create more than one complete event. If the Complete Event fires, all event fires in all classes. I want that it only the event fires who was in the class where the call was made.
I hope you understand my description.
Update:
i solve my Problem with remove the event from the eventhandler in the Complete Event.
Related
I have a game with many classes that need to listen to events. But under certain circumstances, those classes are destroyed or disabled. When that happens, I need to remove their listening methods from the events manager delegate table.
I don't want to modify the EventsManager and I would like to each class that adds any events to it to know which events it added.
I'm currently using something like this do add and remove the events in each class:
void AddEventsListeners() {
EventsManager.AddListener<OnClickDown>(OnClickDownHandler);
EventsManager.AddListener<OnClickUp>(OnClickUpHandler);
EventsManager.AddListener<OnClick>(OnClickHandler);
}
void RemoveEventsListeners() {
EventsManager.RemoveListener<OnClickDown>(OnClickDownHandler);
EventsManager.RemoveListener<OnClickUp>(OnClickUpHandler);
EventsManager.RemoveListener<OnClick>(OnClickHandler);
}
Those OnClick are all derived from GameEventBase, and the OnClickHandler are methods declared as
void OnClickDown(OnClickHandler e) {}
to match the delegate that is used in the EventsManager, which is declared as
delegate void EventDelegate<T>(T e) where T : GameEventBase;
I want to be able to fill a special hash table named, say, events, that has keyvalue pairs like
<T, EventDelegate<T>> where T: GameEventBase
That is, I want to be able to do events.add(OnClick, OnClickHandler), where OnClickHandler is declared as
OnClickHandler(OnClick e) {}
And I want adding to fail if OnClickHandler where defined, for example, as
OnClickHandler(OtherGameEventBaseDerivedEvent e) {}
That requirement translates to me wanting type safety in that special dictionary.
One of my attempts involved not a dictionary, but a way to decide which method to call, between the AddListener and RemoveListener
I didn't like it because it introduces a parameter to the method and the code reads really weird with it. It does work, and does reduce the repetition, but is too ugly.
I create a AddOrRemoveAllListeners(AddOrRemove addOrRemove), which I populated with calls to AddOrRemoveListener for each event.
Now all I had to do is AddOrRemoveAllListeners(AddOrRemove.Remove) or AddOrRemoveAllListeners(AddOrRemove.Add), to add or remove my events.
enum AddOrRemove {
Remove,
Add
}
void AddOrRemoveListener<T>(EventsManager.EventDelegate<T> del, AddOrRemove addOrRemove)
where T : GameEventBase {
switch (addOrRemove) {
case AddOrRemove.Remove:
EvMan.RemoveListener<T>(del);
break;
case AddOrRemove.Add:
EvMan.AddListener<T>(del);
break;
}
}
Another attempt involved creating the type
class EventsDictionary<T> : Dictionary<T, EventsManager.EventDelegate<T>> where T : GameEventBase { }
And using it like this:
EventsDictionary<GameEventBase> events = new MyCustomDictionary<GameEventBase>();
void AddEventHandlerPairToEventsDictionary<T>(T e, EventsManager.EventDelegate<T> handler) where T : GameEventBase {
if (!events.ContainsKey(e)) {
events.Add(e, handler);
}
}
But the events.Add(e, handler) fails and forces me to declare the handler as
EventsManager.EventDelegate<GameEventBase>
instead of
EventsManager.EventDelegate<T>
If I do that, I could add keyvalue pairs that don't make sense in that events type, i.e., I lose the event handling type safety.
I want to have such a structure because I don't like all those repetitions. It would be really bad if someone forgot to remove an event in the RemoveEventsListeners().
Having such a dictionary, I could use a foreach loop to add/remove the handlers to the EventsManager, which would be really nice.
As for performance, this is for a game and it needs to have good performance. Those adding/removing of events can happen a lot (sometimes hundreds of times per frame) because a lot of objects are destroyed (can't leave null handlers in the EventsManager) or disabled (need to stop listening to everything until enabled again) all the time. This means reflection and lots of casting/boxing or anything that creates lots of garbage collected objects is out.
I'm, of course, open to suggestions as to other ways to approach this.
Thanks for your assistance!
I'm attaching the relevant parts of the EventsManager being used (The RemoveListener() is analogous to the AddListener). The GameEventBase is just an empty shell. It isn't a .NET event nor uses EventArgs.
public class EventsManager : ManagedBase {
public delegate void EventDelegate<T>(T e) where T : GameEventBase;
private delegate void EventDelegate(GameEventBase e);
private readonly Dictionary<Type, EventDelegate> delegates = new Dictionary<Type, EventDelegate>();
private readonly Dictionary<Delegate, EventDelegate> delegateLookup = new Dictionary<Delegate, EventDelegate>();
public void AddListener<T>(EventDelegate<T> del) where T : GameEventBase {
// Early-out if we've already registered this delegate
if (delegateLookup.ContainsKey(del)) {
return;
}
// Create a new non-generic delegate which calls our generic one.
// This is the delegate we actually invoke.
EventDelegate internalDelegate = (e) => del((T) e);
delegateLookup[del] = internalDelegate;
EventDelegate tempDel;
if (delegates.TryGetValue(typeof (T), out tempDel)) {
delegates[typeof (T)] = tempDel + internalDelegate;
}
else {
delegates[typeof (T)] = internalDelegate;
}
}
public void Raise(GameEventBase e) {
EventDelegate del;
if (delegates.TryGetValue(e.GetType(), out del)) {
del.Invoke(e);
}
}
}
Your problems seem to be solved if you use the EventAggregator pattern.
There is a short description of it by Martin Fowler
Some very good implementations of it already exist, for example in caliburn micro and
Microsoft Prism
The general idea is that you simplify event registration and deregistration and have a single source of events for many objects.
I never had performance issues with it. You simply put a _eventAggregator.Subscribe(this) when you want to start listening to events for an object and Unsubscribe if you want to stop. Whereever you want to fire an event, just publish it, EventAggregator does the routing.
This once again looks like an XY problem. OP seems to want to have a central place to handle event handlers, registration and disposal. The OP has gone down the route of trying to create a pattern that deal with this in a generic way, but has not looked into the state of the art regarding how this problem is typically solved. He has now come up against a problem in his design and is now asking for a solution to THAT problem, rather than the original problem of event handlers.
There are two good solutions to event handler registration lifecycle management that I know of in .net.
Weak Event Handler
You state that "It would be really bad if someone forgot to remove an event in the RemoveEventsListeners()." Yet do not actually mention WHY it is bad. Typically the only reason for this being bad is that the event handler will now keep an object in reference, that should be collected. With weak reference event handlers, the GC will still be able to collect your object, even when it subscribes to an object that is still alive.
Rx.Net
Rx.Net abstracts event registrations into IDisposables, which you can tie to the object's lifetime, assuming of course you want to control the lifetime of the registrations.
However I actually find the IObservable pattern much nicer to work with than event handler pattern, mostly because C# lacks first class support for event handlers (this is not the case with F#).
F#
Most of your problems will have stemmed from the short sighted design of events keyword handling in C# (specifically not making events a first class construct). F# however does support first class events, and thus should be able to support the pattern you are trying to construct.
Thus with this option you should scrap your code base and rewrite it in F#.
*EDIT added tongue in cheek option of rewriting in F#.
I'm trying to design a client / server solution. Currently it contains three projects. The client, the server, and a library that each use (because they both require a lot of the same stuff).
For example, both the client and the server (in this case) read incoming data in the exact same way. Because of this, both the client and the server have their own MessageReader object. The MessageReader will first read the first 4 bytes of incoming stream data to determine the length of the data and then read the rest. This is all performed asynchronously. When all the data is read the class raises its own MessageRead event or if there was an IOException while reading it raises its own ConnectionLost event.
So this all works fine. What's the problem? Well, the client and the server are a bit different. For example, while they may read data in the same way, they do not write data in the same way. The server has a Dictionary of clients and has a Broadcast method to write to all clients. The client only has a single TcpClient and can only Write to the server. Currently all this behavior is within each respective WinForm and I want to move it to a Client and Server class but I'm having some problems.
For example, remember earlier when I was talking about the MessageReader and how it can raise both a MessageRead event and a ConnectionLost event? Well, now there's a bit of a problem because in designing the Client class I have to capture these two events and re-raise them because the client form should not have access to the MessageReader class. It's a bit ugly and looks like this:
class Client
{
private MessageReader messageReader = new MessageReader();
public delegate void MessageReceivedHandler(string message);
public delegate void ConnectionLostHandler(string message);
public event ConnectionLostHandler ConnectionLost;
public event MessageReceivedHandler MessageReceived;
public Client()
{
messageReader.ConnectionLost += messageReader_ConnectionLost;
messageReader.MessageReceived += messageReader_MessageReceived;
}
private void messageReader_MessageReceived(string message)
{
if (ConnectionLost != null)
{
ConnectionLost(message);
}
}
private void messageReader_ConnectionLost(string message)
{
if (MessageReceived != null)
{
MessageReceived(message);
}
}
}
This code is ugly because its basically duplicate code. When the MessageReader raises the MessageReceieved handler the Client has to capture it and basically re-raise its own version (duplicate code) because the client form should not have access to the message reader.
Not really of a good way to solve it. I suppose both Client and Server could derive from an abstract DataReader but I don't think a client is a data reader, nor is the server. I feel like composition makes more logical sense but I can't figure out a way to do this without a lot of code duplication and confusing event handlers.
Ouch, this question is getting a bit long.. I hope I don't scare anyone away with the length. It's probably a simple question but I'm not really sure what to do.
Thanks for reading.
Composition.
I didn't even read your code or text. I find that the average developer (almost) never needs inheritance but they like to use it quite a bit.
Inheritance is fragile. Inheritance is hard to get correct. It's harder to keep it in check with SOLID.
Composition is easy to understand, easy to change, and easy to DI, Mock, and test.
SOLID
I ended up using inheritance for this even though the relationship wasn't strong. The code duplication it got rid of was worth it. Was able to place all the events both classes shared in to the base class.
This may fall into the category of method extending, overriding or polymorphism (I'm new to C# and OO so forgive me, I'm still learning :-) ).
I have an app that is utilizing a 3rd party API. Within the API there is a method for right click+select action on a custom control (the control is an image viewer where a user can right click and cycle to another image that exists within the parent group).
In my limited understanding I would think one of these 2 things would need to happen (whether either one can be done or whether either one is a good solution is up in the air!)
I don't want to override the existing method, I just want to append to it somehow.
If there was a way I could detect when the specific event was triggered and completed, then call my method. Set up some kind of listener if thats available.
Thanks!!
As you didn't post any reference, I'll try to outline some ways.
if there is an event
CustomControl cc = yourCustomControl;
cc.SelectionCompleted += (sender, args) => { YourMethod() };
This is using an anomynous event handler using a lambda.
Another way would be:
public class Form1 : Form
{
public Form1()
{
this.cc.SelectionCompleted += HandlerSelectionCompleted;
}
public void HandlerSelectionCompleted(object sender, EventArgs e)
{
YourCustomMethod();
}
}
there is a method to override
public class YourCustomControl : CustomControl
{
public override void Selection()
{
base.Selection(); // first call the original method
// now do some custom stuff
}
}
You can not override that method: that's right, if it's not protected/virtual/abstract whatever, or if you can not derive from that component's class.
You can search the component for the events and guess (if there is no any documentation) which event is fired after your desired action. And actually execute the code in that event handle.
There could be other "hacking" tricks, but I personally would avoid to do something like that, if not for personal passion, but focus on reachitecturing my program, in order to fit the requirements and support that component, as much as I can.
Regards.
What you are describing is a tenant of Aspect Oriented Programming AOP. If you want to instrument a 3rd party .NET dll, I would recommend PostSharp http://www.sharpcrafters.com/solutions/logging
I'm probably just being neurotic, but I regularly find myself in situations in which I have class that publishes an event, and I find it convenient to subscribe to this event from within the class itself (e.g. in the constructor), rather than only subscribing from external classes.
This sounds reasonable to me, but I can't help the nagging feeling that it's a poor practice, for the simple reason that I'm always faced with the question: "Why not perform the actions that you'd provide in the event handler in the code which fires the event?"
public class Button
{
public Button()
{
this.Click += someHandler; // bad practice?
}
public event EventHandler Click;
public void HandleInput()
{
if (someInputCondition)
{
// Perform necessary actions here rather than
// subscribing in the constructor?
this.Click(this, ...);
}
}
}
Are there any drawbacks to subscribing to your own events?
This sounds reasonable to me, but I can't help the nagging feeling that it's a poor practice, for the simple reason that I'm always faced with the question: "Why not perform the actions that you'd provide in the event handler in the code which fires the event?"
To answer that question, consider partial class scenarios. Suppose you have a base type B. You run an automated tool that decorates B by extending it to derived class D. Your tool generates a partial class so that developers consuming D can further customize it for their own purposes.
In that case, it seems perfectly reasonable that the user-authored side of D would want to sign up to be called when events declared by B or the machine-generated side of D are raised by the machine-generated side of D.
That was the scenario we found ourselves in when designing VSTO many years ago. As it turns out, it was not difficult to do this in C# but it was quite tricky to get it all working in VB. I believe VB has made some tweaks to their event subscription model to make this easier.
That said: if you can avoid this, I would. If you're just making an event for internal subscription that seems like a bad code smell. Partial methods in C# 3 help out greatly here, since they make it easy and low-cost for the machine-generated side to call little notification functions in the user-generated side, without having to go to the trouble of publishing an event.
I see no problem with this. But if you handle the events in the same class you could also override the event method:
protected override void OnClick(Eventargs e)
{
base.OnClick(e);
}
This is more efficient and gives you the power to swallow the event if necessary (simply not calling base.OnClick()).
There's a very exotic problem due to internal optimization when doing this. Due to the optimization adding/removing event handlers is not thread safe. It only applies to events that are used by the declaring type like in your example.
Fortunately this has been changed with 4.0, but if you're on previous version, you could experience this.
The issue is that “someHandler” will change the state of your object. Do you want this state changing before or after any “external” code is run by the event?
It is not clear at what point the state change will be make if you subscribe to the event, however calling it in “HandleInput()” make it a lot clearer when it will be called.
(Also it is more normal to call “HandleInput()”, “OnClick” and make it virtual so sub classes can override it)
After saying the above, normally there is no great harm in subscribing to your own event; in UI classes that represent forms it is very common, otherwise it tend to “surprise” a lot of people that read your code.
If your button class should be the first which receives the click event, you should write your code in the event method, eg.:
protected virtual void OnClick(EventArgs e)
{
//insert your code here
if(this.Click != null)
{
this.Click(this, e);
}
}
but if it's not necessary that your class is the first reciever, you can subscribe to the event normally.
if you take the ordinary System.Windows.Form class as an example,
when you want to handle the Form_Load event (using visual studio designer), it is handled
in the class of the Form itself !
this.Load += new System.EventHandler(this.Form1_Load);
private void Form1_Load(object sender, EventArgs e)
{
}
so i think it is not a problem at all !!.
I am .Net developer. i want to know that is there any event handling mechanism in Java for Events Handling like C#.
what i want to do is i want to raise/fire an event form my class upon some condition. and consumer of this class should register that event and write event handling method.
this can be done easily in C#. i have to implement this thing in Java.
after googling out i found some links but all those are talking about GUI events in AWT and swing.
can any one help me out.
Although most of the examples will be to do with GUI events, the principles are basically the same. You basically want an interface or abstract class to represent a handler for the event, e.g.
public interface EventHandler
{
// Change signature as appropriate of course
void handleEvent(Object sender, EventArgs e);
}
then the publisher of the event would have:
public void addEventHandler(EventHandler handler)
public void removeEventHandler(EventHandler handler)
It would either keep a list of event handlers itself, or possibly have them encapsulated in a reusable type. Then when the event occurs, you just call handleEvent in each handler in turn.
You can think of delegate types in C# as being very similar to single-method interfaces in Java, and events are really just an add/remove pair of methods.
I love C# Events,
They are simple to use and convenient. i missed them in java so wrote a small utility class that mimics the very basics of C# Event.
using java 8 (for lambdas)
no += operator, instead call .addListener((x) -> ...)
to trigger an event, call .broadcast(<EventArgs insance>)
Online Demo - https://repl.it/DvEo/2
Event.java
import java.util.HashSet;
import java.util.Set;
import java.util.function.Consumer;
public class Event {
private Set<Consumer<EventArgs>> listeners = new HashSet();
public void addListener(Consumer<EventArgs> listener) {
listeners.add(listener);
}
public void broadcast(EventArgs args) {
listeners.forEach(x -> x.accept(args));
}
}
You may want com.google.common.collect.Sets.newConcurrentHashSet() for thread safety
EventArgs.java
public class EventArgs {
}
Java has support through various event handling implementations - the simple Observer/Observable in java.util, PropertyChangeEvents in java.beans, and GUI events which inherit from AWTEvent.
An Observable object has a list of observers which implement the Observer interface, and mechanisms for adding and removing observers. If o.notifyObservers(x) is called on the observable, update(o,x) will be called on each observer. This mechanism is somewhat old fashioned and rarely used in new code - it dates from Java 1.0 before EventObject was added in Java 1.1 and better event handling added for AWT and beans.
Beans and GUI events propagate an object which extends java.util.EventObject to listeners which implement a sub-interface of EventListener. Usually if you're using an existing API you will only care about the events and listeners for that API, but if you're defining an API the events and listeners should follow that convention.
It's also the convention in Java APIs to call the handlers for events "listeners" rather than handlers, and all listener interface names end with Listener. The names of the methods don't start with 'on' but should be past tense -mouseMoved or handshakeCompleted rather than onMouseMove or handleMouseMove.
The PropertyChangeSupport class provides an implementation of the mechanism for adding and removing listeners from a bean, and is also used for properties of Swing widgets.
If you write your own listener handling, it's conventional to allow listeners to remove themselves by calling source.removeXXXListener(this) from within their event handling method. Just iterating over a simple collection of listeners and calling their handling methods would give a ConcurrentModificationException with in these cases - you need to copy the collection of listeners or use a concurrently modifiable collection.
Check out this tutorial. It goes through some of the Swing event handling stuff that you have come across in your searches, but the concepts are pretty general. In simple terms, event handlers maintain a collection of listeners (implementing an interface) and iterate over them when they fire an event, calling the method in the interface.