C# .NET proper event subscribing and un-subscribing - c#

I have an application that runs continuously, it creates and destroys classes some of which have events like mouse click events and the like...
First question is what is the proper way to unsubscribe? If the subscribe looks like this:
Panel1.MouseClick += new MouseEventHandler(Action_MouseClick);
is it proper to unsubscribe like this:
Panel1.MouseClick -= new MouseEventHandler(Action_MouseClick);
OR is it ok to do this:
Panel1.MouseClick -= Action_MouseClick;
or is either way ok?
My other question is is If I use the Microsoft Visual C# studio to create the events through the designer, does it automatically unsubscribe as part of the 'Dispose' method? Or do I still need to put the unsubscribe method in the code?

Either way of unsubscribing will have the same effect, and both are correct.
As for your other question .. if you use the designer to create events for controls on a form, when the form is disposed the source of the events no longer exists, so they won't be called. I guess I'm saying it isn't necessary to detach those events.

My other question is is If I use the
Microsoft Visual C# studio to create
the events through the designer, does
it automatically unsubscribe as part
of the 'Dispose' method? Or do I still
need to put the unsubscribe method in
the code?
From memory: no, it won't generate the un-subscribe code.
You can double check this yourself by opening the classname.designer.cs file and examining the generated Dispose method.

The designer code won't automatically unsubscribe, but the subscriptions should not keep the controls alive as long as the form and all of its controls are no longer accessible from the application code. Lingering event handlers are mainly a problem when the subscriber and event producer have different lifetimes, which generally shouldn't be the case for a Form and its controls.
If you create/remove controls dynamically, you will probably want to manage the events, though it's not strictly necessary if the removed controls are no longer referenced and the removed controls stop firing events.

Related

Unloaded event not called in Secondary View in UWP app targeting 10240

Following this example, https://learn.microsoft.com/en-us/windows/uwp/design/layout/show-multiple-views If I open any view in a secondary view, the Unloaded event of the Page opened in the Secondary Window never gets called. So there are many objects that are left without disposing properly, as I have some cleanup code in the Unloaded event.
I know that I can use the Consolidated event in the view to know when the secondary view is closed (Because the Closed event never gets called in the Window) But I cannot use this as I have some custom buttons that need to be unloaded before closing the secondary views. I can make some dirty patches but I want to avoid this. Any thoughts?
But I cannot use this as I have some custom buttons that need to be unloaded before closing the secondary views.
The unloaded event will not be fired when you close the window. I did not understand why you could not use the Consolidated event. According to your description, you just want to do some clean operation before the window is closed. The ApplicationView.Consolidated Event occurs when the window is removed from the list of recently used apps, or if the user executes a close gesture on it. It exactly meets your requirement.
You could check the official MultipleViews sample. It implements a ViewLifetimeControl.cs to control your secondary views and implements the release events and relevant functions to keep track of the secondary views and destroying the objects when closing.

C# : How do I determine the name of the event that was fired and its event/delegate type?

I'm leveraging on a legacy and unsupported third party API. From what I know, all of its methods return nothing but fires events instead. For a particular method, I have tried hook up event handlers to all the possible events that the method could fire based on the docs but the program didn't run through any of it.
In Visual Studio 2017, is it possible to check which event was fired and also its type (e.g., delegate type)?
What I've tried
I've tried looking into the diagnostics tools part of the IDE but nothing seems to mention the name of event that was fired-it only shows the name of the event handler IF it was hooked up to an event. But for this scenario, I couldn't hook up an event handler to that event because I don't know the name of the event that was fired by the method and its type.
So best if the solution also provides a way to find out the type of that event.
Yes, the Diagnostics Tools of visual studio should provide you with what you are looking for.
There is this section about Application insights or UI analysis events.
it's in Debug, Windows, Show Diagnostic Tools. It should be with other window settings really to be easily found.
You can try my Runtime Flow extension to see all executed method and event handler names. Then you can probably infer the name of the event that was fired.

Execute code when form loaded and before Form closes

I'm currently working on an application that uses a Windows Form GUI. The main work of the application will be performed on an additional thread - but it is possible that it will be dependent on the state of the form.
Because of this, before I create the thread I must make sure that the form is completely loaded. Also, I need to make sure the thread is terminated before the form begins closing.
Possible solutions for this problem might be overriding the OnShown and OnFormClosing methods.
Does the OnShow method really gets called only after ALL of the assets of the form have been loaded? And what about the OnFormClosing - can I be sure that any code executed in this method will be performed before the form begins close / dispose?
I suggest you read through the WinForms event ordering as posted on MSDN:
http://msdn.microsoft.com/en-us/library/86faxx0d.aspx
Windows Forms events can be tricky, and the order they fire unreliable. For example, the 'Shown' event is meant to fire once and once only, when the Form is first displayed, but just yesterday I found a way to completely prevent that event from firing by manipulating Form.Visible flags at the right time.
So, you need to be quite specific about your needs. For example - when you say 'completely loaded', what do you mean? Controls created, form visible, Form constructor finished executing?
Likewise, the FormClosing event might be circumvented by an unhandled exception in your main aUI thread, which results in the Form being removed without the event firing.
I suggest never assuming anything around these events. Make your worker thread capable of dealing with the Form state being unavailable, or not ready. Without knowing your exact requirements, it's hard to be more specific.
Have you tried to use InitializeComponent on the constructor of your main WinForm and use OnLoad (called whenever everything is loaded)?

c# Winform best way to update form?

I am trying to update a selected record using this code when closing the form:
interestsTableAdapter.Update(newCityCollectionDataSet);
The record is NOT updating doing this. I use the same code to update datagridviews but I do it while it is validating. Is there a better way to do this with FORMS as opposed to controls?
Why this isn't working could depend on when you're trying to save your record. There's a big difference between executing code before your form's closing and while your form's closing.
Typically, failures while the form's closing (in handlers of a Form's FormClosed event) are caused by the application exiting before the handler gets a chance to do its job.
On the other hand, handlers of a Form's FormClosing event are invoked before the form even starts to close, and can even keep it from closing. These handlers are almost always waited for, as long as the form is the application's "main" or "startup" form (and not a child of it).
Without seeing more code than what you've provided, I'm afraid it's all I can do to advise you to execute your code before the form closes (via its FormClosing event), rather than while it's closing (via its FormClosed event).

How to view/monitor which events are being fired from controls on a user interface

I am creating an GUI using winforms in C#, all the controls have numerous events. I would like to know which of these events are being fired and when. One way would be to put debug statements on each of the event handlers but that would require too much work. Is there any way of doing this in Visual Studio 2008/2010 or are there any tools that can help?
Runtime Flow (developed by me) with the monitoring filter "Module == System.Windows.Forms.dll && Function == On*" will show what events are firing for all winforms controls.
Managed Spy has possibility to log all events of chosen control. See this article where
you can read about this tool and download it.
If you don't mind some information overload, you could use Spy++ (\Common7\Tools\Spyxx.exe) to see all the windows messages generated by the application.
Some of the window messages translates more or less directly to .net events...
You could write a logging class that subscribes to these events and write the event plus the time stamp into a log file.
It still requires that you write some code, but it's independent of your production code and shouldn't affect it any way.

Categories

Resources