I have been using Events instead of delegates in my MonoTouch project, typically using this pattern (iPhone app using Storyboards):
I call PerformSegue to present a new View Controller, and in PrepareForSegue method, I set the View Controller's properties and subscribe to its events using a lambda expression as such:
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier.Equals("NextViewControllerSegue")) {
using (MyNextViewController destinationVC = segue.DestinationViewController as MyNextViewController) {
destinationVC.SomeProperty = "some value";
destinationVC.Cancelled += (s, e) => {
this.DismissViewController(false, null);
};
}
}
}
(as an aside, I chain these Cancelled events where I need to close a hierarchy of View Controllers - whether this is good or bad is a question for another day)
My question is: I recently discovered that if you don't unsubscribe from an object's events, that object is not Garbage Collected. So I have changed the above code to:
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
if (segue.Identifier.Equals("NextViewControllerSegue")) {
using (MyNextViewController destinationVC = segue.DestinationViewController as MyNextViewController) {
destinationVC.SomeProperty = "some value";
destinationVC.Cancelled += Cancel;
}
}
}
protected void Cancel (object sender, EventArgs e)
{
(sender as MyNextViewController).Cancelled -= Cancel;
this.DismissViewController(false, null);
}
My question is this: is this pattern a good way to go about things? And will approach 2 (unsubscribing from the event in the event delegate) work? I am not sure where else to unsubscribe. Or should I move everything to use a notification pattern instead (as suggested here: Should I prefer NSNotificactionCenter or .NET events when using Monotouch?)?
In your first example, the event will cause the destinationVC to have a reference to this. Since this is most likely lower in the stack than destinationVC in a navigation controller, you don't really have an issue because destinationVC doesn't live as long as this.
Your second example isn't needed in your example, but it would be if:
A controller subscribes to an event on an object that will be around for a long time, like a Model/ViewModel class
A controller subscribes to an event on a previous controller in a navigation controller stack (same goes for modal controllers)
Related
I have the following problem.
I created an event and subscribe to it, now I want that the UI changes when the Event triggers.
using System;
using MintWebApp.Data;
using MintWebApp.Models;
using Microsoft.AspNetCore.Components;
namespace WebApp.UI.Core
{
public partial class AppHeader
{
public string status { get; set; }
[Inject]
public StateService state { get; set; }
EventHandler<string> onStatusChanged= (sender, eventArgs) => {
//Here i get the error, I can't access this and status
status = eventArgs;
this.StateHasChanged();
Console.WriteLine(eventArgs.PatientName);
};
protected override void OnInitialized() => state.StatusHandler += onStatusChanged;
}
}
I get this Error
A field initializer cannot reference the non-static field, method, or property 'AppHeader.patientContext'
Keyword 'this' is not available in the current context
How can I subscripe to an event and update the UI
This needs to be approached a bit differently as the EventHandler<T> type doesn't work as expected here. (At Least not for me)
First off, for the EventArgs, remember that this is a type, so you can't assign them to the Status property (which you have as a string) without a cast. The way to do this is to define your own arguments type that derives from EventArgs, something like this:
public class PatientEventArgs: EventArgs
{
public string PatientName {get; set;}
public string StatusValue {get; set;}
}
Next for the handler method that you need to use, set it up as an async method. I found that the async was important so you can use an InvokeAsync farther down and avoid an exception when the thread and dispatcher don't agree, as in other windows open or other users signed in elsewhere, through this post:
Discussion on thread vs. Synchronization Context
private async void OnStatusChanged(object sender, EventArgs e) {
// Make sure the args are the type you are expecting
if(e.GetType() == typeof(PatientEventArgs))
//Cast to the correct Args type to access properties
var patientStatus = e as PatientEvendArgs;
status = patientStatus.StatusValue;
Console.Writeline(patientStatus.PatientName);
/* Use InvokeAsync method with await to make sure
StateHasChanged runs correctly here without interfering with another
thread (open window or other users) */
await InvokeAsync(() => StateHasChanged());
}
Next, and important to your scenario, you will hit a wall with the Partial Class declaration as you have it since you need to implement IDisposable to clean up after yourself as the component tears down. Instead, use an inheritance structure as follows and use the OnInitialized and Dispose overrides
AppHeader.razor.cs
public class AppHeaderBase : OwningComponentBase
{
// OnStatusChanged method as described above
protected override void OnInitialized() //Can use the Async version as well
{
// Unsubscribe once to make sure you are only connected once
// Prevents event propogation
// If this component is not subscribed this doesn't do anything
state.StatusHandler -= onStatusChanged;
// Subscribe to the event
state.StatusHandler += onStatusChanged;
}
protected override void Dispose(bool disposing)
{
// Unsubscribe on teardown, prevent event propogation and memory leaks
state.StatusHandler -= onStatusChanged;
}
}
This takes advantage of some built in Blazor features in OwningComponentBase and includes a Dispose Method, while doing a much better job of managing your Dependency Injection for you.
Further reading HERE (Note that I didn't go too deep on this for this example as it's using a singleton, but worth the reading to understand DI lifetimes in Blazor)
And then in your AppHeader.razor
....
#inherits AppHeaderBase
....
Now when you use the event handler in the StateService from somewhere else, build up a new PatientEventArgs type with the values you need to pass:
var newArgs = new PatientEventArgs(){
PatientName = "SomeName",
StatusValue = "SomeStatus"
};
And pass it in as needed in your code:
state.OnStatusChanged(this, newArgs);
Or direct from Razor syntax:
<button #onclick="#(() => state.OnStatusChanged(this, new PatientEventArgs(){ PatientName = "SomeName", StatusValue = "SomeStatus"})">Sender Button</button>
This should multicast your event out as needed, and all subscribers should pick it up and update.
Here is a quick working demo if needed, adapted from another version of this I've been working on.
I'm writing a program that logs user idle time, however when I attempt to run the program it throws a Stack Overflow Exception.
These are my custom events
public void OnInactive(EventArgs e)
{
this.OnInactive(new EventArgs());
do
{
var idle2 = GetIdleTime();
GetIdleTime();
System.Diagnostics.Debug.WriteLine(idle2);
}
while (timer.Interval > 5000);
}
public void OnActive(EventArgs e)
{
this.OnActive(new EventArgs());
if (timer.Interval < 5000)
{
var idle3 = GetIdleTime();
System.Diagnostics.Debug.WriteLine(idle3);
}
}
I've breakpointed the code to try and locate the source of the issue, which appears to lie within this.OnInactive(new EventArgs());, However I'm pretty stumped on how to resolve this issue as I'm a beginner to Custom Events and haven't been coding in C# for long.
Any and all help with this issue would be greatly appreciated!
Thanks in Advance =]
Your handler method is calling itself immediately on entry:
this.OnInactive(new EventArgs());
this leads to a sequence of calls:
OnInactive -> OnInactive -> OnInactive -> ... ->
which will continue until you run out of stack space and the StackOverflowException is thrown by the runtime.
It's not clear what you're trying to achieve with the recursive call, but you should be able to just remove it.
You have the same issue in your OnActive handler.
EDIT: In response to the comments, it seems you're trying to raise the event itself at the beginning of your method. Assuming your event declaration looks like:
public event EventHandler InActive;
then you can raise it with:
EventHandler inactiveEvent = this.InActive;
if(inactiveEvent != null)
{
inactiveEvent(this, e);
}
and similarly for your Active event.
I gues you are trying to call the base method, but in fact you are now calling OnInactive when hitting OnInactive. This behaviour is recursive and will finaly stop due StackOverflow exception.
You can call the base function with base.<function name>.
For example:
class SpecialDerived : Base
{
public override void Say()
{
Console.WriteLine("Called from Special Derived.");
base.Say();
}
}
More info: http://msdn.microsoft.com/en-us/library/hfw7t1ce(v=vs.71).aspx
I think what you need is a bit more understanding about events. Let me explain the same through a sample code.
Class A{
public event OnInactive;
public event OnActive;
}
when any changes occur in classA you want to update things in ClassB. So you will implement events of class A in ClassB.
this link will describe you the same in detail.
My understanding says that there is no use of events when you are triggering it from the same class and listening in the same class.
these aren't event handlers, these are the methods that are going to
be called in order to raise the active and inactive events – Reece
Cottam
You need to actually call the event.
public class ReecesWatcher
{
public event EventHandler ActiveEvent;
public event EventHandler InactiveEvent;
protected virtual void OnInactive(EventArgs e)
{
// Fire the event using the () syntax. Fire it through
// a test variable so that we can reliabilty test for null,
// if there are no subscribers.
EventHandler inactiveEventTest = InactiveEvent;
if (inactiveEventTest != null)
{
inactiveEventTest(this, new EventArgs());
}
do
{
var idle2 = GetIdleTime();
GetIdleTime();
System.Diagnostics.Debug.WriteLine(idle2);
}
while (timer.Interval > 5000);
}
protected virtual void OnActive(EventArgs e)
{
// Fire the event using the () syntax. Fire it through
// a test variable so that we can reliabilty test for null,
// if there are no subscribers.
EventHandler activeEventTest = ActiveEvent;
if (activeEventTest != null)
{
activeEventTest(this, new EventArgs());
}
if (timer.Interval < 5000)
{
var idle3 = GetIdleTime();
System.Diagnostics.Debug.WriteLine(idle3);
}
}
// ... the rest of your class, where you call OnActive and OnInactive to
// cause the events to be fired.
}
I recommend not making your OnActive and OnInactive methods public, otherwise you're exposing too much of the implementation to the rest of your program. If you expect the class to be inherited from, then make them protected, otherwise I usually make them entirely private, since they're basically wrapper functions called by the rest of the class.
I have a UserControl on a Form,
when I MouseMove on that UserControl I want to do something in the Form.
How can I make the Form 'listen' for this event?
I am using Visual C#, .Net framework 3.5, winforms
I suppose you're referring to a use control or something like that.
You can add a public event, and trigger it inside your class when detecting the inner class event.
Then you have to subscribe to the published event in the second class.
This is a sample so that you see the sintax:
public class WithEvent
{
// this is the new published event
public EventHandler<EventArgs> NewMouseEvent;
// This handles the original mouse event of the inner class
public void OriginalEventhandler(object sender, EventArgs e)
{
// this raises the published event (if susbcribedby any handler)
if (NewMouseEvent != null)
{
NewMouseEvent(this, e);
}
}
}
public class Subscriber
{
public void Handler(object sender, EventArgs e)
{
// this is the second class handler
}
public void Subscribe()
{
WithEvent we = new WithEvent();
// This is how you subscribe the handler of the second class
we.NewMouseEvent += Handler;
}
}
If you are talking about Windows Forms (it's not clear from the question) you need to define
a new event in the class who recieves the mouse-event. After reciving it raises a new custom-event. Another class is subcribed to that (custom-event) a recieves notification.
For moe information (it's not something that can be presenteed in a couple of lines)
can have alook here:
How to propagate an Event up to the MainForm?
If you are talking about WPF, there are different concept of events: event routing. If your class is UI element present in UI tree of the component that recieves actually mouse-event, it will be propagated to your class too. So no need of more coding.
To expand a little on the answer from JotaBe, there are two scenarios that I could see you having:
a) class A calls a method in class B, and an exception happens. In this case, you don't need to do anything: exception will walk the stack, until it finds a catch statement. So, really, all you need to do is NOT catch an exception, or if you do need to catch it (for logging purposes and such), then rethrow it.
b) if you need to have a code triggered in some unrelated class, as a result of exception, then the best way is to use events. In your class declare:
public class ClassA
{
public static event EventHandler<Exception> OnException;
public void Notify(Exception ex)
{
if (OnException != null)
{
OnException(this, ex);
}
}
}
and then, in order to be notified, all you need is to
ClassA.OnException += (sender, exeption) =>
{
... some GetHashCode ..
};
... I guess JotaBe already added all necessary example code as I was typing
I have a static generic class that helps me move events around with very little overhead:
public static class MessageBus<T> where T : EventArgs
{
public static event EventHandler<T> MessageReceived;
public static void SendMessage(object sender, T message)
{
if (MessageReceived != null)
MessageReceived(sender, message);
}
}
To create a system-wide message bus, I simply need to define an EventArgs class to pass around any arbitrary bits of information:
class MyEventArgs : EventArgs
{
public string Message { get; set; }
}
Anywhere I'm interested in this event, I just wire up a handler:
MessageBus<MyEventArgs>.MessageReceived += (s,e) => DoSomething();
Likewise, triggering the event is just as easy:
MessageBus<MyEventArgs>.SendMessage(this, new MyEventArgs() {Message="hi mom"});
Using MessageBus and a custom EventArgs class lets me have an application wide message sink for a specific type of message. This comes in handy when you have several forms that, for example, display customer information and maybe a couple forms that update that information. None of the forms know about each other and none of them need to be wired to a static "super class".
I have a couple questions:
fxCop complains about using static methods with generics, but this is exactly what I'm after here. I want there to be exactly one MessageBus for each type of message handled. Using a static with a generic saves me from writing all the code that would maintain the list of MessageBus objects.
Are the listening objects being kept "alive" via the MessageReceived event?
For instance, perhaps I have this code in a Form.Load event:
MessageBus<CustomerChangedEventArgs>.MessageReceived += (s,e) => DoReload();
When the Form is Closed, is the Form being retained in memory because MessageReceived has a reference to its DoReload method? Should I be removing the reference when the form closes:
MessageBus<CustomerChangedEventArgs>.MessageReceived -= (s,e) => DoReload();
Well, yes, you should, but if you use the lambda syntax as you've done in your example I think it won't work (by which I mean, the handler will not be de-registered successfully).
Someone correct me if I'm wrong, but I believe this is true because using the lambda syntax effectively creates a new EventHandler<CustomerChangedEventArgs> object, with its own place in memory. When you try to remove this handler, using the lambda syntax again, this creates yet another new EventHandler<CustomerChangedEventArgs> object, which is not equal to the first one you created; and so the first one never gets de-registered.
Sadly, I think you'll need to actually define a method like this:
DoReload(object sender, CustomerChangedEventArgs e) {
DoReload(); // your original overload, which doesn't actually care
// about the sender and e parameters
}
This way you can do:
MessageBus<CustomerChangedEventArgs>.MessageReceived += DoReload;
And later:
MessageBus<CustomerChangedEventArgs>.MessageReceived -= DoReload;
Yes, there are problems. Your event handlers will cause the form object to stay referenced, you have to explicitly unregister the event handlers. The lambdas make this impossible, you'll have to write an explicit handler.
This pattern has a name, "Event Broker service". It is part of the Composite UI Application Block, published by Microsoft's Pattern and Practices team. Beg, borrow and steal (if not use) what you can from this.
You could use weak references to store the event handlers. That way, unhooked handlers won't prevent garbage collection of the objects.
public static class MessageBus<T> where T : EventArgs
{
private static List<WeakReference> _handlers = new List<WeakReference>();
public static event EventHandler<T> MessageReceived
{
add
{
_handlers.Add(new WeakReference(value));
}
remove
{
// also remove "dead" (garbage collected) handlers
_handlers.RemoveAll(wh => !wh.IsAlive || wh.Target.Equals(value));
}
}
public static void SendMessage(object sender, T message)
{
foreach(var weakHandler in _handlers)
{
if (weakHandler.IsAlive)
{
var handler = weakHandler.Target as EventHandler<T>;
handler(sender, message);
}
}
}
}
This question already has answers here:
How to ensure an event is only subscribed to once
(8 answers)
Closed 8 years ago.
Duplicate of: How to ensure an event is only subscribed to once
and Has an event handler already been added?
I have a singleton that provides some service and my classes hook into some events on it, sometimes a class is hooking twice to the event and then gets called twice.
I'm looking for a classical way to prevent this from happening. somehow I need to check if I've already hooked to this event...
How about just removing the event first with -= , if it is not found an exception is not thrown
/// -= Removes the event if it has been already added, this prevents multiple firing of the event
((System.Windows.Forms.WebBrowser)sender).Document.Click -= new System.Windows.Forms.HtmlElementEventHandler(testii);
((System.Windows.Forms.WebBrowser)sender).Document.Click += new System.Windows.Forms.HtmlElementEventHandler(testii);
Explicitly implement the event and check the invocation list. You'll also need to check for null:
using System.Linq; // Required for the .Contains call below:
...
private EventHandler foo;
public event EventHandler Foo
{
add
{
if (foo == null || !foo.GetInvocationList().Contains(value))
{
foo += value;
}
}
remove
{
foo -= value;
}
}
Using the code above, if a caller subscribes to the event multiple times, it will simply be ignored.
I've tested each solution and the best one (considering performance) is:
private EventHandler _foo;
public event EventHandler Foo {
add {
_foo -= value;
_foo += value;
}
remove {
_foo -= value;
}
}
No Linq using required. No need to check for null before cancelling a subscription (see MS EventHandler for details). No need to remember to do the unsubscription everywhere.
You really should handle this at the sink level and not the source level. That is, don't prescribe event handler logic at the event source - leave that to the handlers (the sinks) themselves.
As the developer of a service, who are you to say that sinks can only register once? What if they want to register twice for some reason? And if you are trying to correct bugs in the sinks by modifying the source, it's again a good reason for correcting these issues at the sink-level.
I'm sure you have your reasons; an event source for which duplicate sinks are illegal is not unfathomable. But perhaps you should consider an alternate architecture that leaves the semantics of an event intact.
You need to implement the add and remove accessors on the event, and then check the target list of the delegate, or store the targets in a list.
In the add method, you can use the Delegate.GetInvocationList method to obtain a list of the targets already added to the delegate.
Since delegates are defined to compare equal if they're linked to the same method on the same target object, you could probably run through that list and compare, and if you find none that compares equal, you add the new one.
Here's sample code, compile as console application:
using System;
using System.Linq;
namespace DemoApp
{
public class TestClass
{
private EventHandler _Test;
public event EventHandler Test
{
add
{
if (_Test == null || !_Test.GetInvocationList().Contains(value))
_Test += value;
}
remove
{
_Test -= value;
}
}
public void OnTest()
{
if (_Test != null)
_Test(this, EventArgs.Empty);
}
}
class Program
{
static void Main()
{
TestClass tc = new TestClass();
tc.Test += tc_Test;
tc.Test += tc_Test;
tc.OnTest();
Console.In.ReadLine();
}
static void tc_Test(object sender, EventArgs e)
{
Console.Out.WriteLine("tc_Test called");
}
}
}
Output:
tc_Test called
(ie. only once)
Microsoft's Reactive Extensions (Rx) framework can also be used to do "subscribe only once".
Given a mouse event foo.Clicked, here's how to subscribe and receive only a single invocation:
Observable.FromEvent<MouseEventArgs>(foo, nameof(foo.Clicked))
.Take(1)
.Subscribe(MyHandler);
...
private void MyHandler(IEvent<MouseEventArgs> eventInfo)
{
// This will be called just once!
var sender = eventInfo.Sender;
var args = eventInfo.EventArgs;
}
In addition to providing "subscribe once" functionality, the RX approach offers the ability to compose events together or filter events. It's quite nifty.
Create an Action instead of an event. Your class may look like:
public class MyClass
{
// sender arguments <----- Use this action instead of an event
public Action<object, EventArgs> OnSomeEventOccured;
public void SomeMethod()
{
if(OnSomeEventOccured!=null)
OnSomeEventOccured(this, null);
}
}
have your singleton object check it's list of who it notifies and only call once if duplicated. Alternatively if possible reject event attachment request.
In silverlight you need to say e.Handled = true; in the event code.
void image_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
e.Handled = true; //this fixes the double event fire problem.
string name = (e.OriginalSource as Image).Tag.ToString();
DoSomething(name);
}
Please tick me if this helps.