C# Event subscription to method - c#

I am attempting to subscribe two events to an object. But the object is not instantiated before I try to add the events. Is there a way I can subscribe these two events and instantiate afterwards? I already have the delegates, event, event args and event handler working.
Sample Code:
Ares a;
public B()
{
a.up += new upEventHandler(doUp);
a.down += new downEventHandler(doDown);
a = new Ares();
}

I am attempting to subscribe two events to an object. But the object is not instantiated before I try to add the events. Is there a way I can subscribe these two events and instantiate afterwards?
No, absolutely not. It's exactly like trying to set properties on an object before the object exists. Try to think about how that would work - and then realize that subscribed event handlers are part of the state of an object just like properties are.
Obviously you could store the event handlers somewhere else and subscribe them later on, but as stated, the answer is simply no. It doesn't make any sense at a conceptual level, or a practical one.

It's not possible. You must instantiate the object first.

The closest thing you could do to what you're describing would be to make the events static.
class Ares {
public static event upEventHandler up;
public static event downEventHandler down;
// ...
}
And then modify B() to be:
public B() {
Ares.up += new upEventHandler(doUp);
Ares.down += new downEventHandler(doDown);
a = new Ares();
}

I assume that the events are fired in the constructor and you want to capture that.
Try refactoring the event firing code out of the constructor into a separate Initialize() method, so you would then have the following:
Ares a;
public B()
{
a = new Ares();
a.up += new upEventHandler(doUp);
a.down += new downEventHandler(doDown);
a.Initialize(); //do all init of the ares object here, not in constructor
}

Related

Temporarily stop form events from either being raised or being handled?

I have a ton on controls on a form, and there is a specific time when I want to stop all of my events from being handled for the time being. Usually I just do something like this if I don't want certain events handled:
private bool myOpRunning = false;
private void OpFunction()
{
myOpRunning = true;
// do stuff
myOpRunning = false;
}
private void someHandler(object sender, EventArgs e)
{
if (myOpRunning) return;
// otherwise, do things
}
But I have A LOT of handlers I need to update. Just curious if .NET has a quicker way than having to update each handler method.
You will have to create your own mechanism to do this. It's not too bad though. Consider adding another layer of abstraction. For example, a simple class called FilteredEventHandler that checks the state of myOpRunning and either calls the real event handler, or suppresses the event. The class would look something like this:
public sealed class FilteredEventHandler
{
private readonly Func<bool> supressEvent;
private readonly EventHandler realEvent;
public FilteredEventHandler(Func<bool> supressEvent, EventHandler eventToRaise)
{
this.supressEvent = supressEvent;
this.realEvent = eventToRaise;
}
//Checks the "supress" flag and either call the real event handler, or skip it
public void FakeEventHandler(object sender, EventArgs e)
{
if (!this.supressEvent())
{
this.realEvent(sender, e);
}
}
}
Then when you hook up the event, do this:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
When WhateverEvent gets raised, it will call the FilteredEventHandler.FakeEventHandler method. That method will check the flag and either call, or not call the real event handler. This is pretty much logically the same as what you're already doing, but the code that checks the myOpRunning flag is in only one place instead of sprinkled all over your code.
Edit to answer question in the comments:
Now, this example is a bit incomplete. It's a little difficult to unsubscribe from the event completely because you lose the reference to the FilteredEventHandler that's hooked up. For example, you can't do:
this.Control.WhateverEvent += new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler;
//Some other stuff. . .
this.Control.WhateverEvent -= new FilteredEventHandler(() => myOpRunning, RealEventHandler).FakeEventHandler; //Not gonna work!
because you're hooking up one delegate and unhooking a completely different one! Granted, both delegates are the FakeEventHandler method, but that's an instance method and they belong to two completely different FilteredEventHandler objects.
Somehow, you need to get a reference to the first FilteredEventHandler that you constructed in order to unhook. Something like this would work, but it involves keeping track of a bunch of FilteredEventHandler objects which is probably no better than the original problem you're trying to solve:
FilteredEventHandler filter1 = new FilteredEventHandler(() => myOpRunning, RealEventHandler);
this.Control.WhateverEvent += filter1.FakeEventHandler;
//Code that does other stuff. . .
this.Control.WhateverEvent -= filter1.FakeEventHandler;
What I would do, in this case, is to have the FilteredEventHandler.FakeEventHandler method pass its 'this' reference to the RealEventHandler. This involves changing the signature of the RealEventHandler to either take another parameter:
public void RealEventHandler(object sender, EventArgs e, FilteredEventHandler filter);
or changing it to take an EventArgs subclass that you create that holds a reference to the FilteredEventHandler. This is the better way to do it
public void RealEventHandler(object sender, FilteredEventArgs e);
//Also change the signature of the FilteredEventHandler constructor:
public FilteredEventHandler(Func<bool> supressEvent, EventHandler<FilteredEventArgs> eventToRaise)
{
//. . .
}
//Finally, change the FakeEventHandler method to call the real event and pass a reference to itself
this.realEvent(sender, new FilteredEventArgs(e, this)); //Pass the original event args + a reference to this specific FilteredEventHandler
Now the RealEventHandler that gets called can unsubscribe itself because it has a reference to the correct FilteredEventHandler object that got passed in to its parameters.
My final advice, though is to not do any of this! Neolisk nailed it in the comments. Doing something complicated like this is a sign that there's a problem with the design. It will be difficult for anybody who needs to maintain this code in the future (even you, suprisingly!) to figure out the non-standard plumbing involved.
Usually when you're subscribing to events, you do it once and forget it - especially in a GUI program.
You can do it with reflection ...
public static void UnregisterAllEvents(object objectWithEvents)
{
Type theType = objectWithEvents.GetType();
//Even though the events are public, the FieldInfo associated with them is private
foreach (System.Reflection.FieldInfo field in theType.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance))
{
//eventInfo will be null if this is a normal field and not an event.
System.Reflection.EventInfo eventInfo = theType.GetEvent(field.Name);
if (eventInfo != null)
{
MulticastDelegate multicastDelegate = field.GetValue(objectWithEvents) as MulticastDelegate;
if (multicastDelegate != null)
{
foreach (Delegate _delegate in multicastDelegate.GetInvocationList())
{
eventInfo.RemoveEventHandler(objectWithEvents, _delegate);
}
}
}
}
}
You could just disable the container where all these controls are put in. For example, if you put them in a GroupBox or Panel simply use: groupbox.Enabled = false; or panel.Enabled = false;. You could also disable the form From1.Enabled = false; and show a wait cursor. You can still copy and paste these controls in a container other than the form.

Would the following pattern of unsubscribing your self from an event via closure cause any problems?

Consider the situation in which you want to subscribe to an event for one and only one notification. Once the first notification lands, you unsubscribe from all future events. Would the following pattern present any memory issues? It works, but I wasn't sure if the self-referencing closure could keeps things around in memory longer than desired.
public class Entity
{
public event EventHandler NotifyEvent;
}
// And then, elsewhere, for a listen-once handler, we might do this:
Entity entity = new Entity();
Action<object, EventArgs> listener = null;
listener = (sender, args) =>
{
// do something interesting
// unsubscribe, so we only get 1 event notification
entity.NotifyEvent -= new EventHandler(listener);
};
entity.NotifyEvent += new EventHandler(listener);
Note that you have to declare 'listener' and assign a value (null). Otherwise the compiler complains about 'Use of unassigned local variable listener'
There is nothing wrong with this pattern. It's the very same pattern I and many others use for assigning and removing a lambda expression to an event handler.
While I think the general pattern is fine, I wouldn't go through Action<object, EventArgs>. I'd use:
EventHandler listener = null;
listener = (sender, args) =>
{
// do something interesting
// unsubscribe, so we only get 1 event notification
entity.NotifyEvent -= listener;
};
entity.NotifyEvent += listener;

FileSystemWatcher Events Untouchable by System.Delegate?

I am writing integration tests that involve FileSystemWatcher objects. To make things easier, I want to unsubscribe everything from an event delegate without having to hunt down every subscription. I already saw related post, Is it necessary to unsubscribe from events?. This is somewhat a duplicate, but I am specifically asking why this doesn't work with a FileSystemWatcher object.
It would be nice to do something like the following:
private void MethodName()
{
var watcher = new FileSystemWatcher(#"C:\Temp");
watcher.Changed += new FileSystemEventHandler(watcher_Changed);
watcher.Changed = null; // A simple solution that smells of C++.
// A very C#-ish solution:
foreach (FileSystemEventHandler eventDelegate in
watcher.Changed.GetInvocationList())
watcher.Changed -= eventDelegate;
}
No matter how the Changed event is referenced, the compiler reports:
The event 'System.IO.FileSystemWatcher.Changed' can only appear on the left hand side of += or -=
The above code works just fine, when working with an event in the same class:
public event FileSystemEventHandler MyFileSystemEvent;
private void MethodName()
{
MyFileSystemEvent += new FileSystemEventHandler(watcher_Changed);
MyFileSystemEvent = null; // This works.
// This works, too.
foreach (FileSystemEventHandler eventDelegate in
MyFileSystemEvent.GetInvocationList())
watcher.Changed -= eventDelegate;
}
So, what am I missing? It seems that I should be able to do the same with the FileSystemWatcher events.
When you declare event in your class, it is an equivalent (almost) of the following code:
private FileSystemEventHandler _eventBackingField;
public event FileSystemEventHandler MyFileSystemEvent
{
add
{
_eventBackingField =
(FileSystemEventHandler)Delegate.Combine(_eventBackingField, value);
}
remove
{
_eventBackingField =
(FileSystemEventHandler)Delegate.Remove(_eventBackingField, value);
}
}
Notice that there is no set or get accessor for event (like for properties) and you can't explicitly write them.
When you write MyFileSystemEvent = null in your class, it is actually doing _eventBackingField = null, but outside your class there is no way to directly set this variable, you have only event add & remove accessors.
This might be a confusing behavior, because inside your class you can reference an event handler delegate by event name, and can't do that outside the class.
Short answer is += and -= are public operators while = is a private operator to the class that's declaring the event.

C# clone EventHandler

I have a class with multiple EventHandlers (among other things):
public GameObject
{
public event EventHandler<EventArgs> Initialize;
public event EventHandler<EventArgs> BeginStep;
....
}
I want to be able to add a Clone() function to GameObject, which returns an exact duplicate of the object it was called on. I tried doing it like this:
public GameObject Clone()
{
var clone = new GameObject()
{
Initialize = this.Initialize,
BeginStep = this.BeginStep,
};
}
But, it appears that it is making clone.BeginStep point to the same object as this.BeginStep instead of making a copy. So, how do I make a copy of an EventHandler object?
You don't need to worry about that. The EventHandler<EventArgs> object is immutable so any change in the list of listeners in either object will cause that object to get a new EventHandler<EventArgs> instance containing the updated invocation list. This change will not be present in the other GameObject.
Try adding it with the += operator. I didn't even know it was possible to assign an event.
clone.Initialize += this.Initialize;
Also, all delegates are immutable value types, therefore you don't have to worry about them pointing to the same object - when you an operation like above, the whole delegate is copied (cloned, if you will).
It depends on whether your events are delegating to methods defined in the GameObject class or whether they delegate to to some other observer class instance.
If the events are handled in methods defined in your GameObject class and you want events in the clone to be handled by methods in your clone instance, you can get use reflection to get the method info from the original event handlers, create a new delegate using the cloned instance and the method name, and then assign the new delegate as the cloned event handler.
public GameObject Clone()
{
var clone = new GameObject();
foreach (var target in this.Initialize.GetInvocationList())
{
var mi = target.Method;
var del = Delegate.CreateDelegate(
typeof(EventHandler<EventArgs>), clone, mi.Name);
clone.Initialize += (EventHandler<EventArgs>)del;
}
return clone;
}
If the events are handled in a different class, then you don't need to do anything, but all event notifications for both the original instance and cloned instance willhave the same handlers. If that's not what you want then you'll need to change the event delegates after you clone.
You don't need to clone the events, just like you don't need to clone any methods of the source object. When you clone, all you really need to duplicate are the member/property values.
You'll want to do something akin to what was posted on Deep cloning objects
public static GameObject Clone(GameObject source)
{
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(GameObject);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (GameObject)formatter.Deserialize(stream);
}
}
Your class will need to be serializable.
EDIT: As I said, it was based off of the code I linked to, and I hurried to give the answer. Should've checked it a little closer.

How to expose an event in a c# class?

I am building a simple class to hold related methods. Part of this code includes synchronising to a database. The built in SyncOrchestrator class includes a SessionProgress event handler which I can wire up an event to.
What I would like to do is instance my class and then hook up an some code to this event so that I can display a progress bar (ill be using BGWorker).
So, my question is probably c# 101, but how do I expose this event through my class the correct way so that I can wire it up?
Thanks
I think you're looking for something like this:
(I also suggest you read the Events tutorial on MSDN.)
public class SyncOrchestrator
{
// ...
public event EventHandler<MyEventArgs> SessionProgress;
protected virtual void OnSessionProgress(MyEventArgs e)
{
// Note the use of a temporary variable here to make the event raisin
// thread-safe; may or may not be necessary in your case.
var evt = this.SessionProgress;
if (evt != null)
evt (this, e);
}
// ...
}
where the MyEventArgs type is derived from the EventArgs base type and contains your progress information.
You raise the event from within the class by calling OnSessionProgress(...).
Register your event handler in any consumer class by doing:
// myMethodDelegate can just be the name of a method of appropiate signature,
// since C# 2.0 does auto-conversion to the delegate.
foo.SessionProgress += myMethodDelegate;
Similarly, use -= to unregister the event; often not explicitly required.
Like this:
public event EventHandlerDelegate EventName;
EventHandlerDelegate should obviously be the name of a delegate type that you expect people to provide to the event handler like so:
anObject.EventName += new EventHandlerDelegate(SomeMethod);
When calling the event, make sure you use this pattern:
var h = EventName;
if (h != null)
h(...);
Otherwise you risk the event handler becoming null in between your test and actually calling the event.
Also, see the official documentation on MSDN.

Categories