Clear All Event subscriptions (Clone linked) - c#

I just implemented Clone from ICloneable and realized that the event subscriptions from my source instance also followed. Is there a good way to clear all those?
Currently I am using a couple of these loops for every event I have to clear everything.
foreach (var eventhandler in OnIdChanged.GetInvocationList())
{
OnIdChanged -= (ItemEventHandler) eventhandler;
}
foreach (var eventhandler in OnNameChanged.GetInvocationList())
{
...
This works fine but clutters the code a bit. Mostly worried to get event dangling.

I think you could just set OnIdChanged = null in your cloned object.
After you have created the clone you just call the ClearEvents method on the clone.
public class ClonedObject
{
public event EventHandler OnIdChanged;
public event EventHandler OnNameChanged;
public void ClearEvents()
{
OnIdChanged = null;
OnNameChanged = null;
}
}

Presumably, if you truly wanted to clone an object, you wanted to keep those event subscriptions.
If you're cloning objects that shouldn't be subscribed to events, it appears you should consider refactoring your code. Have your controller or similar objects subscribe to the events with a reference to a dedicated data object and have your data objects store that data without referencing the events; clone the data objects and place them in appropriate controller objects as necessary.
Ultimately, I'm suggesting you get around the issue by not subscribing to events to which you don't need to subscribe. Look at the problem space from a different angle.

Related

Where to unsubscribe events in an attached property?

I have an attached property to use in a datagrid to can use the SelectedItems in my view model. The code is this:
public class DataGridSelectedItemsAttachedProperty
{
#region SelectedItems
///
/// SelectedItems Attached Dependency Property
///
public static readonly DependencyProperty SelectedItemsProperty =
DependencyProperty.RegisterAttached("SelectedItems", typeof(IList),
typeof(DataGridSelectedItemsAttachedProperty),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
new PropertyChangedCallback(OnSelectedItemsChanged)));
public static IList GetSelectedItems(DependencyObject d)
{
return (IList)d.GetValue(SelectedItemsProperty);
}
public static void SetSelectedItems(DependencyObject d, IList value)
{
d.SetValue(SelectedItemsProperty, value);
}
private static void OnSelectedItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
DataGrid miDg = (DataGrid)d;
miDg.SelectionChanged += dataGrid_SelectionChanged;
miDg.Unloaded += dataGrid_Unloaded;
}
private static void dataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataGrid miDg = (DataGrid)sender;
//Get list box's selected items.
IEnumerable miDgSelectedItems = miDg.SelectedItems;
//Get list from model
IList ModelSelectedItems = GetSelectedItems(miDg);
//Update the model
ModelSelectedItems.Clear();
if (miDg.SelectedItems != null)
{
foreach (var item in miDg.SelectedItems)
ModelSelectedItems.Add(item);
}
SetSelectedItems(miDg, ModelSelectedItems);
}
private static void dataGrid_Unloaded(object sender, RoutedEventArgs e)
{
DataGrid miDg = sender as DataGrid;
miDg.SelectionChanged -= dataGrid_SelectionChanged;
miDg.Unloaded -= dataGrid_Unloaded;
}
#endregion
}
The problem is that this datagrid is in a tab control the event unload is fired, so the event is unsubcribe and then the SelectedItems is not notified to the view model anymore.
So I would like to know how to solve this problem, perhaps unsubscribe the events in another place instead of the unload event?
Thanks.
I have faced the same question, but come to the conclustion that it is unnecessary to unsubscribe from events in this case (thanks for comments from Álvaro García and Blechdose that point me in this direction).
Actualy memory leaks because of an event handler are a one way problem. The cause of this problem is described here: https://stackoverflow.com/a/4526840/12797700. By using this code miDg.SelectionChanged += dataGrid_SelectionChanged; you add a link to the object that stores the dataGrid_SelectionChanged method into the miDg object. Because of that GC cannot remove the object that stores dataGrid_SelectionChanged method while the miDg object is alive.
However, the static object know nothing about the miDg object and GC can remove the miDg object even if the event is handled.
You can download the test project demonstrating this behavior using the next link. It also demonstrates how to replicate the memory leaks problem by handling an event.
https://github.com/Drreamer/AttachedPropertyMemoryTest
when I close the user control is when the attached property will be recolected because no object is referencing it.
This is false. If you remove the code that unregisters the events, any controls using the attached property will live forever. Why? Because the event handlers you register are static. That means the control will contain a reference to something static preventing the garbage collector from ever collecting it.
The first potential solution to this problem is to use the weak event pattern when registering events. It's for the reason above that I always use the weak event pattern when registering events for my own attached properties.
The annoying thing about this solution is that it requires a rather large amount of boilerplate code. You have to create a new WeakEventManager implementation for every new type of event. Then to receive the weak events, you have to implement an interface (EDIT: unless you are using .NET 4.5 or higher), and that means you can't have a static handler. So then you need class that implements the IWeakEventListner interface, and create and manage instances of that class in your attached property events.
Therefore, the solution I would recommend for you is to actually subclass the DataGrid class and add this functionality as a normal dependency property. If you do it that way, you won't have to register events at all (there are protected methods you can override), and there's no worries about potential memory leaks. The reason I would recommend this solution is because in my experience I have needed to override the DataGrid class for numerous other reasons, many of them could be achieved with attached properties, but a few of them cannot.
The real problem is that the WPF DataGrid implementation is rather half-baked (my personal opinion). There are bugs, default behaviors that I don't like, and incomplete or unimplemented features (such as support for Copy, but not Paste; or the particular issue I think you are trying to solve: a bindable SelectedItems). It's possible to fix all these issues most easily by simply subclassing DataGrid.

C# - issue with custom raising events

I have my class where I define my event:
public class EventRaiserUtility
{
public event EventHandler updateList;
public void updateListEvent()
{
if (updateList != null)
{
updateList(this, EventArgs.Empty);
}
}
public static EventRaiserUtility raiser = new EventRaiserUtility();
}
and this is where I raise my event:
EventRaiserUtility.raiser.updateListEvent();
and finally this is where I'm trying to create the listener:
...
EventRaiserUtility.raiser.updateList += new EventHandler(raiser_updateList);
//placed in the init method of another class
...
private void raiser_updateList(object sender, EventArgs e)
{
connType = MainWindowViewModel.getTTC();
}
Simply: this event has to notify when a list is updated and then update another list, with getTTC() with raiser_updateList.
But raiser_updateList is never called. Why? All my 3 snippets of code are in 3 different classes (same project), but this isn't a problem... right?
You're creating a new EventRaiserUtility just before you call updateListEvent (which should have a capital U to follow .NET conventions, by the way; ditto updateList => UpdateList) - but you're creating a separate EventRaiserUtility in order to subscribe to the event. They're different objects, so have different event subscribers. If you always create a new object before raising the event, there could never be any subscribers.
You should have a single EventRaiserUtility stored in an instance variable in the containing class - you'd create that on construction, then subscribe to the event in one place an raise it in another... but because they'd be talking about the same EventRaiserUtility object, you wouldn't lose the subscription.
(It's not clear that this utility class actually has much value, to be honest - why aren't you just declaring the event in your class directly? And why declare your own delegate when EventHandler has exactly the same signature?)
As far as I can see - you are subscribing to the event of one instance of EventRaiserUtility, but raising event from another instance which has no subscribers
you need one object to really own the event. Maybe that is the EventRaiserUtility, but you'd still need to make the same instance available in both classes. Without knowing the relationship between those classes

Forwarding events to selected instance

Is there a good strategy to exchange the receiver of multiple events (let's say an object instance A) during runtime to another instance B (or multiple instances)? For example think of a menu bar with a bunch of operations that can be performed on the currently selected of multiple objects.
Now one option would be to connect all object's handlers to the click events and let the handlers filter out the relevant calls (by checking if the current instance is selected) or registering/unregistering the events on selection.
Another one would be to register the events to an object functioning as proxy like this (rough code):
class ClickEventProxy
{
private static ClickEventProxy selectedInstance; // <-- changend on selection
public event EventHandler SomeEventToForward;
public static void RaiseSomeEventToForward(object sender, EventArgs e)
{
if (selectedInstance.ClickedAddNewFrame != null)
selectedInstance.ClickedAddNewFrame(sender, e);
}
...
}
The sender-site would look like SomeSource.Click += ClickEventProxy.RaiseSomeEventToForward; and all receivers would subscribe to their instance of the proxy.
However handling the instances (e.g. by a global <object, proxy instance> dictionary) is a bit unconvenient and the whole thing looks a bit clumsy. So my question: Is there a more programmatic way to do so? Or is it itself bad practice proxying events by introducing another step and one should rather remove and readd the handlers? (Maybe this could be made better by using custom events and altering the invocation list...)

Why public event cannot be invoked outside directly?

Consider we have a class with event declared:
public class FooBar
{
public event EventHandler FooBarEvent;
}
Despite of "publicness" of the event, we cannot call FooBarEvent.Invoke from outside.
This is overcame by modyfing a class with the following approach:
public class FooBar
{
public event EventHandler FooBarEvent;
public void RaiseFooBarEvent(object sender, EventArgs eventArguments)
{
FooBarEvent.Invoke(sender, eventArguments);
}
}
Why accessing public events outside is limited by adding and removing listeners only?
Defining a public event merely gives consumers the ability to subscribe and unsubscribe from it. The ability to raise the event is limited to the type hierarchy which declares the event.
Allowing all subscribers to also be able to raise the event would be a bit chaotic. Imagine for example I had a TextBox class which had a Focused event. If any old consumer could raise the event then the Focused event could easily fire when the TextBox class wasn't actually focused. This would make it nearly impossible to maintain any type of invariant during an event.
Personally I think this is done to properly convey the design principles behind the whole events architecture.
The purpose of an event is to notify a listener of said event occurring in a given object.
What's the point of raising events of classes that don't belong to you?
That's what events are for. If you want to invoke it publicly you probably need delegates not events
Events gives encapsulation,
It prevents other classes from assigning anything to it
It prevents passing it as a parameter to methods
It prevents assigning it to any variable
It prevents calling it from another classes (not even derived classes have access to it)
etc
public accessibility tells that it can be subscribed from anywhere, not invoked from anywhere.
the answer to your question is
An event in C# is a way for a class to provide notifications to clients of that class when some interesting thing happens to an object.
Invoking the event from outside doesn't makes sense therefore it is not allowed.
I think you should change your perspective on how events work. Other classes shouldn't "own" the event and trigger it. Classes which "listen" to the event by "subscribing" to it and do a certain action when this event occurs.
That's the way the language is defined - an event can only be fired by the owning class. If you must fire it from a different class, have the owning class define a public method that will fire the event:
public FireFooBarEvent (object sender, EventArgs args)
{
if(FooBarEvent != null)
FooBarEvent(sender, args);
}
And call this method from any class.

Mixing enums with event classes in an event aggregator

I attempted to implement my own simple event aggregator recently. I got a lot of inspiration from the event aggregator article on MSDN. There is one thing that I notice about the event aggregator on MSDN is the events are actually classes on their own. This isn't really a bad thing at all. However, I just find it awkward to always create a new empty class for every single little event.
The reason I find it awkward is because of the need to create a class for every single granular event. A mouse click event, for instance, would have double_click, single_click, left_click, right_click, etc. And all of these are going to have a class of its own. It gets messy after a while.
So in my own implementation, I thought I could make it in such a way where the ClickEvent is a class, but all the granular events related to the Click event would then be "types" of the ClickEvent. In this case, the "types" are enum. The usage would look something like this:
//Publisher
eventAggregator.GetEvent<ClickEvent>.Publish(ClickEventType.Double_Click, eventArgs);
//Subscriber
eventAggregator.GetEvent<ClickEvent>.Subscribe(ClickEventType.Double_Click, handlerMethod);
However, I'm not sure if this implementation defeats the whole purpose of having a strongly typed event? Now, it seems like the ClickEvent is merely a container for the different event enum types.
Yes it does (seem like a container that is) - your handler will fire regardless of the click type and there will be some code required in the handler to determine the type of click, which makes things a little messier.
If your issue is mostly the organisation of the files/classes and keeping the code tidy, why not just create the click events as nested classes within a main click class
e.g.
public static class ClickEvents // Prevent instantiation
{
public class SingleLeft { }
public class SingleRight { }
public class DoubleLeft { }
public class DoubleRight { }
// Are there any more click events possible?!
}
eventAggregator.GetEvent<ClickEvents.SingleLeft>.Publish();
Aside from that, it's the uniqueness of the type that determines the event signature, and therefore multiple types are required to satisfy this particular implementation
At least the above keeps your handler code clean
void HandleLeftClick()
{
}
vs
void HandleClick(ClickArgs e)
{
if(e.ClickType == ClickType.Left)
{
}
}
Edit:
Also remember that you can subscribe multiple events to the same handler if you want to handle more than one click type:
eventAggregator.GetEvent<ClickEvents.SingleLeft>.Subscribe(HandlerMethod);
eventAggregator.GetEvent<ClickEvents.SingleRight>.Subscribe(HandlerMethod);
(this would work in the rare situation that the subscriber didn't care which mouse button was clicked)
I think you missed one possibility. You see, you don't have to create a new class for each notification. Instead, you are free to reuse classes but carry some additional state of arbitrary complexity inside.
public class MouseClickNotification {
public bool IsDoubleClick;
public MouseButton ClickedButton;
// any additional stuff
This way it is you who precisely define the granularity of your notification model.

Categories