I have a hardware ware device that needs to be unloaded at the end of program execution or it will be left in an undefined/unstable/dangerous state. This is easy enough during normal operation, but during any sort of crash or unexpected circumstance, it usually doesn't get unloaded properly.
Searching, I found that I can setup an event to clean up the board on process exit, or at least a fraction of them:
public MainForm()
{
...
AppDomain.CurrentDomain.ProcessExit += new EventHandler(OnProcessExit);
...
}
static void OnProcessExit(object sender, EventArgs e)
{ myHardwareDevice.checkAndPerformSafeShutdown();
}
where checkAndPerformSafeShutdown is a wrapper around native dll function call that cleans up the driver and puts all hardware in a safe state. However, this fails to compile with:
error CS0120: An object reference is required for the non-static field, method, or property 'projectNme.MainForm.myHardwareDevice'.
What is the scope of this event handler and why is it different then any other event handler in the class? Is there someway I can get a reference to the hardware device?
Define the event handler as an instance method on your MainForm and you'll have access to all instance variables.
Related
I'm starting out in C#, coded a lot in Java but having some trouble here. I'm trying to learn how to use MouseKeyHook for an application I'm developing. I cannot get the actual listener to fire off an event. Here's my listener code:
using System;
using System.Windows.Forms;
using Gma.System.MouseKeyHook;
namespace ChromaHeatmap
{
class keyListener
{
private IKeyboardMouseEvents m_GlobalHook;
public void Subscribe()
{
// Note: for the application hook, use the Hook.AppEvents() instead
m_GlobalHook = Hook.GlobalEvents();
m_GlobalHook.KeyPress += GlobalHookKeyPress;
}
private void GlobalHookKeyPress(object sender, KeyPressEventArgs e)
{
Console.WriteLine("blah");
}
public void Unsubscribe()
{
m_GlobalHook.KeyPress -= GlobalHookKeyPress;
//It is recommened to dispose it
m_GlobalHook.Dispose();
}
}
}
And here's the part of my application code where I attempt to do something with the listener. If anyone can let me know what the best way is to loop here and wait for events, I'd appreciate it.
//Listen for key presses
keyListener heyListen = new keyListener();
heyListen.Subscribe();
while(true)
{
}
while(true) {}
This is a hold-and-catch-fire statement, the thread will burn 100% core and cannot execute the hook callback. You'll notice that the machine goes dead for 5 seconds when you press a key, the operating system is waiting for an opportunity to invoke the callback. But it won't wait forever and unceremoniously will destroy the hook so you regain control over the machine. Also the kind of mishap that will occur when you try to debug your event handler.
Windows needs an opportunity to safely call the hook callback. That requires your program to be "idle", not executing any code. The technical term for this is "pumping the message loop", your program must wait for a notification from the operating system that something interesting happened.
A very simple way is to use the Winforms project template as-is, you'll also get a window. Note how the Main() method in the project makes the call that you need instead of the while() loop. You must call Application.Run().
Check this post for code that avoids displaying a window.
I wrote a visual studio extension package that subscribes to DebuggerEvents.OnEnterBreakMode event. But this event is never get raised.
Here is some code:
protected override void Initialize()
{
base.Initialize();
applicationObject = (DTE2) GetService(typeof (DTE));
applicationObject.Events.BuildEvents.OnBuildDone += BuildEventsOnOnBuildDone;
applicationObject.Events.DebuggerEvents.OnEnterBreakMode += DebuggerEventsOnOnEnterBreakMode;
}
But method DebuggerEventsOnOnEnterBreakMode is never called. Method BuildEventsOnOnBuildDone is called.
Why this can happen?
I know this sounds silly but in order to listen to the DebuggerEvents events you need to maintain a reference to DebuggerEvents itself.
DebuggerEvents _debuggerEvents;
protected override void Initialize() {
applicationObject = (DTE2) GetService(typeof (DTE));
_debuggerEvents = applicationObject.Events.DebuggerEvents;
_debuggerEvents.OnEnterBreakMode += DebuggerEventsOnOnEnterBreakMode
The reason for this is subtle. DebuggerEvents is actually a COM / CCW object which is created on demand when the DTE.DebuggerEvents property is accessed. The event handler code doesn't keep the CCW alive hence the next GC potentially collects the DebuggerEvents property and takes the event handler with it.
It's a really strange bug that is specific to CCW and events. I've heard it referred to as "the most vexing bug ever" and it's not far from the truth
I am currently debugging a big (very big!) C# application that contains memory leaks. It mainly uses Winforms for the GUI, though a couple of controls are made in WPF and hosted with an ElementHost. Until now, I have found that many of the memory leaks were caused by events not being unhooked (by calling -=) and I've been able to solve the problem.
However, I just came across a similar problem. There is a class called WorkItem (short lived) which in the constructor registers to events of another class called ClientEntityCache (long lived). The events were never unhooked and I could see in .NET profiler that instances of WorkItem were being kept alive when they shouldn't because of those events. So I decided to make WorkItem implement IDisposable and in the Dispose() function I unhook the events this way:
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
EDIT
Here is the code I use for subscription:
public WorkItem()
{
ClientEntityCache.EntityCacheCleared += ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
I also changed the code for unregistering to not call new EntityCacheClearedEventHandler.
END OF EDIT
I made the calls to Dispose at the proper places in the code that uses WorkItem and when I debug I can see that the function is really being called and I do -= for every event. But I still get a memory leak and my WorkItems still stay alive after being Disposed and in .NET profiler I can see that the instances are kept alive because the event handlers (like EntityCacheClearedEventHandler) still have them in their invocation list. I tried to unhook them more than once (multiple -=) just to make sure they were not hooked more than once but this doesn't help.
Anyone has an idea why this is happening or what I could do to solve the problem?
I suppose I could change the event handlers to use weak delegates but this would require to mess a lot with a big pile of legacy code.
Thanks!
EDIT:
If this helps, here is the root path described by .NET profiler:
lots of things point on ClientEntityCache, which points to EntityCacheClearedEventHandler, which points to Object[], which points to another instance of EntityCacheClearedEventHandler (I don't understand why), which points to WorkItem.
It might be that multiple different delegate functions are wired to the event. Hopefully the following little example will make it clearer as to what I mean.
// Simple class to host the Event
class Test
{
public event EventHandler MyEvent;
}
// Two different methods which will be wired to the Event
static void MyEventHandler1(object sender, EventArgs e)
{
throw new NotImplementedException();
}
static void MyEventHandler2(object sender, EventArgs e)
{
throw new NotImplementedException();
}
[STAThread]
static void Main(string[] args)
{
Test t = new Test();
t.MyEvent += new EventHandler(MyEventHandler1);
t.MyEvent += new EventHandler(MyEventHandler2);
// Break here before removing the event handler and inspect t.MyEvent
t.MyEvent -= new EventHandler(MyEventHandler1);
t.MyEvent -= new EventHandler(MyEventHandler1); // Note this is again MyEventHandler1
}
If you break before the removal of the event handler you can view the invocation list in the debugger. See below, there are 2 handlers, one for MyEventHandler1 and another for the method MyEventHandler2.
Now after removing the MyEventHandler1 twice, MyEventHandler2 is still registered, because there is only one delegate left it looks a little different, it is no longer showing in the list, but until the delegate for MyEventHandler2 is removed it will still be referenced by the event.
When unhooking an event, it needs to be the same delegate. Like this:
public class Foo
{
private MyDelegate Foo = ClientEntityCache_CacheCleared;
public void WorkItem()
{
ClientEntityCache.EntityCacheCleared += Foo;
}
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= Foo;
}
}
The reason is, what you are using is syntactic sugar for this:
public class Foo
{
public void WorkItem()
{
ClientEntityCache.EntityCacheCleared +=
new MyDelegate(ClientEntityCache_CacheCleared);
}
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -=
new MyDelegate(ClientEntityCache_CacheCleared);
}
}
So the -= doesn't unhook the original one you subscribed with because they are different delegates.
Are you unhooking the right reference? When you unhook using -= no error is produced and if you're unhooking events which aren't hooked nothing will happen. However if you add using += you'll get an error if the event is already hooked. Now, this is only a way for you to diagnose the problem but try adding the events instead and if you DONT get an error the problem is that your unhooking the event with the wrong reference.
Dispose won't get called by the GC if the instance is being kept alive by the event handlers, as it is still being referenced by the source of the events.
If you called your Dispose method yourself, the references would then go out of scope.
Maybe try:
public void Dispose()
{
ClientEntityCache.EntityCacheCleared -= ClientEntityCache_CacheCleared;
// Same thing for 10 other events
}
You are creating a new event handler and removing it from the delegate - which effectively does nothing.
Remove the event subscription by removing reference to the original subscribing event method.
You could always just set your eventhandler = delegate {}; In my opinion, that would be better than null.
I am trying to get my IEventAggregator to allow me to publish and event in one module and catch it in another. I have tried my code below in a single module/project and it works great. It only fails when I have one module/project publish the event and another subscribe to it.
I have having my IEventAggregator injected into both modules via unity.
I have 3 projects, two of them have modules (call them A and B) and one is just a plain class library (call it Interfaces)
In class library Interfaces there is this code:
public class RandomTestEvent : CompositePresentationEvent<string>
{
}
In module A there is this code in a button click command (this is really in a View Model in the project):
var evt2 = _eventAggregator.GetEvent<RandomTestEvent>();
evt2.Publish("Testing");
In module B there is this code:
public void Initialize()
{
var evt2 = _eventAggregator.GetEvent<RandomTestEvent>();
evt2.Subscribe(OnRandomThingDone);
}
private void OnRandomThingDone(string obj)
{
MessageBox.Show("Random Event Done With: " + obj);
}
I can trace through and I see Subscribe get called. When I look at Publish geting called the debugger says Subscriptions = 1 (so it knows that the subscription was made, so I don't seem to have 2 different instances of IEventAggregator.)
But OnRandomThingDone never gets called after Publish.
Any Ideas why? (Do I need to post more code? If so let me know.)
Really random guess - your subscriber is getting GC'd before the event is published - since the default behavior of Prism's CompositePresentationEvent is to use WeakReferences for preserving subscriber target references.
So...try calling the Subscribe overload which allows you to specify keepSubscriberReferenceAlive and pass in true.
If your subscriber then receives the event successfully, it means that your class which contains OnRandomThingDone is going out of scope and getting GC'd before the event is published.
Random API reference:
http://msdn.microsoft.com/en-us/library/ff921122(PandP.20).aspx
Actually grimcoder is correct, a weak reference requires a public Action method.
Utilizing a week reference relieves the coder of unsubscribing to the event, this is managed by the GC.
You can however use a strong reference by passing true to keepSubscriberReferenceAlive, which also can speed up your program if a large number of events is called in a short period of time.
For more information on this see: Chapter 9: Communicating Between Loosely Coupled Components Section Subscribing Using Strong References
It has nothing to do with GC since once Subsriber is attached reference to it never dies.
The real problem is due to inaccessibility of the OnRandomThingDone
if MUST be public i.e:
**public** void OnRandomThingDone(string obj)
{
MessageBox.Show("Random Event Done With: " + obj);
}
I am studying events in C# but there are not much articles or information that show me where or what kinda position I'd need to use events in.
Could some one give me real world example that makes them more understandable.
Thanks in advance.
As Chris Gray said, one use is to signal when something has happened that your code didn't directly call. The most common cause here is probably user actions on the GUI. Another example might be an asynchronous operation completing on another thread.
The other reason to use events is when you don't know who might be interested in what has just happened. The class raising the event doesn't need to know (at design time) anything about how many instances of what other classes might be interested.
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
public EventHandler<DidSomethingEventArgs> DidSomething;
private OnDidSomething(DidSomethingEventArgs e) {
if (DidSomething != null)
DidSomething(this, e);
}
}
Obviously, you also need to define the DidSomethingEventArgs class which passes on the relevant data about the event. This also illustrates a common naming convention for events. If the event is called X, then the event is only ever raised in a method called OnX and any data it passes on is an instance of class XEventArgs. Note that an event can be null if no listeners are subscribed to it, hence the check just before we raise the event.
Note that this class knows nothing about what other classes might be interested in the fact that it did something. It simply announces the fact that it has done it.
Multiple classes can then listen out for the event:
class ListenerA {
private Raiser r;
ListenerA(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
And:
class ListenerB {
private Raiser r;
ListenerB(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
Now, when the DoSomething method is called on the Raiser instance, all instances of ListenerA and ListenerB will be informed via the DidSomething event. Note that the listener classes could easily be in different assemblies to the raiser. They need a reference back to the raiser's assembly but it doesn't need a reference to its listeners' assemblies.
Note that the above simple Raiser example may cause you some problems in a multi-threaded program. A more robust example would use something like:
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
#region DidSomething Event
private object _DidSomethingLock = new object();
private EventHandler<DidSomethingEventArgs> _DidSomething;
public EventHandler<DidSomethingEventArgs> DidSomething {
add { lock(_DidSomethinglock) _DidSomething += value; }
remove { lock(_DidSomethinglock) _DidSomething -= value; }
}
OnDidSomething(DidSomethingEventArgs e) {
EventHandler<DidSomethingEventArgs> handler;
lock (_DidSomethingLock)
handler = _DidSomething;
if (handler == null)
return;
try {
DidSomething(this, e);
} catch (Exception ex) {
//Do something with the exception
}
}
#endregion
}
This ensures that another thread adding or removing a listener while you are in the middle of raising the event doesn't cause problems.
The simple listeners used here will also cause memory leaks if instances of the listener classes are being created and destroyed. This is because the Raiser instance gets passed (and stores) a reference to each listener as they subscribe to the event. This is enough to prevent the garbage collector from properly tidying up the listeners when all explicit references to them are removed. The best way round this is probably to make the listeners implement the IDisposable interface and to unsubscribe from the events in the Dispose method. Then you just need to remember to call the Dispose method.
The most practical example I generally see is User Interactivity. Let's use a Button as a specific example. When the button is clicked, you obviously want something to happen. Let's say we call "SaveSettings()". However, we don't want to hard-code "SaveSettings()" into the button. The buttom would be commanding SaveSettings() to occur. Obviously, this prevents the button from being reusable - we can't use a button which calls SaveSettings() anywhere but the settings dialog. To avoid writing the same button code for every button, each one calling a different function, we use an event.
Instead of the button calling a function directly, the button announces that it has been clicked. From there, the button's responsibility is over. Other code can listen for that announcement, or event, and do something specific.
So in our SaveSettings example, the settings dialog code finds the "OK" button and listens for its "I got clicked" announcement, and when it is fired, calls SaveSettings().
Events can become very powerful because any number of different listeners can wait for the same event. Many things can be invoked by the event.
Sure thing. think of an event as the notification that occurs when something completes in the system that your code didn’t directly call. In C# it's really easy to get code to run when an event "fires"
For example when a user presses a button an event will be raised or when a background network operation completes. In C# you use the += semantics to attach to the event that will be “signaled” when the event fires.
I made you a simple C# winforms program – in it I added a button using the Visual Studio “Designer” (I just dragged a button from the Toolbox to the Window).
You’ll see the line “button1.Click” – in this case I want to do something when the “Click” event is raised.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace events
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += new EventHandler(button1_Click);
}
void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hi!");
}
}
}
You’ll also see other kinds of events in practice for example:
Network operation has completed (WebClient.DownloadFileCompleted)
User Interfaces (resizing windows for example)
Timers (set off the timer in 10 minutes)
Let's say you are developing a UI. You create a widget and you add it to the main form. When something happens in your widget, you can use events to trigger some action on the form - disabling other buttons, etc.
Just like how a button's click event works.