Unless I've fundamentally misunderstood the way events and garbage collection work in C#, if an object has subscribed to an event, the event can still be raised on that object, and the event handler executed, even if the object is out of scope and eligible for garbage collection. So my question is this - is there any way for an object's event handler to check whether the object itself is eligible for garbage collection, with a view to ignoring and/or unsubscribing from the event?
45838
If I have the following code:  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass = null;   Will pClass be garbage collected? Or will it hang around still firing its events whenever they occur? Will I need to do the following in order to allow garbage collection?  MyClass pClass = new MyClass(); pClass.MyEvent += MyFunction; pClass.MyEvent -= MyFunction; pClass = null;
76968
I wanted to set some handler for all the unexpected exceptions that I might not have caught inside my code. In Program.Main() I used the following code:  AppDomain.CurrentDomain.UnhandledException     += new UnhandledExceptionEventHandler(ErrorHandler.HandleException);   But it didn't work as I expected. When I started the application in debugging mode and threw an exception it did call the handler, but afterwards the exception helper in Visual Studio popped up as if the exception occurred without any handling. I tried Application.Exit() inside the handler but it didn't work as well.  What I would like to achieve is that the exception is handled with my handler and then the application closes nicely. Is there any other way to do it or am I using the code above in the wrong way?
102352
I have a HashMap (although I guess this question applies to other collections) of objects. From what I understand, when the documentation talks about removing mappings, then it is removing the entry from the hashtable, i.e. not necessarily destroying the actual object. If the only remaining reference to the object is in this table, then will the object get garbage collected?  If I do map.clear() and those objects that were in the table are not referenced anywhere else, will they get garbage collected?  What is the fastest way, to actually remove all entries from the table, but also destroy those objects.
34848
I used to use the implicit call of toString when wanting some debug info about an object, because in case of the object is null it does not throw an Exception.  For instance:    System.out.println("obj: "+obj);   instead of:  System.out.println("obj: "+obj.toString());   Is there any difference apart from the null case? Can the latter case work, when the former does not?  Edit: What exactly is done, in case of the implicit call?
75289
In relation to , I need to check whether a component that will be instantiated by Castle Windsor, can be garbage collected after my code has finished using it. I have tried the suggestion in the answers from the previous question, but it does not seem to work as expected, at least for my code. So I would like to write a unit test that tests whether a specific object instance can be garbage collected after some of my code has run.  Is that possible to do in a reliable way ?   EDIT  I currently have the following test based on Paul Stovell's answer, which succeeds:       [TestMethod]     public void ReleaseTest()     {         WindsorContainer container = new WindsorContainer();         container.Kernel.ReleasePolicy = new NoTrackingReleasePolicy();         container.AddComponentWithLifestyle&lt;ReleaseTester&gt;(LifestyleType.Transient);         Assert.AreEqual(0, ReleaseTester.refCount);         var weakRef = new WeakReference(container.Resolve&lt;ReleaseTester&gt;());         Assert.AreEqual(1, ReleaseTester.refCount);         GC.Collect();         GC.WaitForPendingFinalizers();         Assert.AreEqual(0, ReleaseTester.refCount, "Component not released");     }      private class ReleaseTester     {         public static int refCount = 0;          public ReleaseTester()         {             refCount++;         }          ~ReleaseTester()         {             refCount--;         }     }   Am I right assuming that, based on the test above, I can conclude that Windsor will not leak memory when using the NoTrackingReleasePolicy ?
108218
This is an extension of question from . I just want to verify if the following is actually safe enough for production use.  List&lt;string&gt; lists = new List&lt;string&gt;(); //Code to retrieve lists from DB     foreach (string list in lists) {     Button btn = new Button();     btn.Click += new EventHandler(delegate { MessageBox.Show(list); }); }   I only run through the above once per startup. For now it seems to work alright. As Jon has mentioned about counterintuitive result in some case. So what do I need to watch out here? Will it be ok if the list is run through more than once?
16225
Why does it (apparently) make a difference whether I pass null as an argument directly, or pass an Object that I assigned the value null?  Object testVal = null; test.foo(testVal);    // dispatched to foo(Object) // test.foo(null);    // compilation problem -&gt; "The method foo(String) is ambiguous"     public void foo(String arg) { // More-specific     System.out.println("foo(String)"); }  public void foo(Object arg) { // Generic     System.out.println("foo(Object)"); }   In other words, why is the (commented-out) second call to foo(...) not dispatched to foo(Object)?  Update: I use Java 1.6. I could compile Hemal's code without problems, but mine still doesn't compile. The only difference I see is that Hemal's methods are static while mine are not. But I really don't see why this should make a difference...?  Update 2: Solved. I had another method foo(Runnable) in my class, so the dispatcher couldn't unambiguously select the single most specific method. (See my comment in Hemal's second answer.) Thanks everyone for your help.
34475
I need to copy the subscribers of one event to another event. Can I get the subscribers of an event (like MyEvent[0] returning a delegate)?  If this is not possible I would use the add accessor to add the delegates to a list. Would that be the best solution?
439
Consider:  namespace WindowsApplication1 {     public partial class Form1 : Form     {         public Form1()         {             InitializeComponent();         }          private void button1_Click(object sender, EventArgs e)         {             //int[] val = { 0, 0};             int val;             if (textBox1.Text == "")             {                 MessageBox.Show("Input any no");             }             else             {                 val = Convert.ToInt32(textBox1.Text);                 Thread ot1 = new Thread(new ParameterizedThreadStart(SumData));                 ot1.Start(val);             }         }          private static void ReadData(object state)         {             System.Windows.Forms.Application.Run();         }          void setTextboxText(int result)         {             if (this.InvokeRequired)             {                 this.Invoke(new IntDelegate(SetTextboxTextSafe), new object[] { result });             }             else             {                 SetTextboxTextSafe(result);             }         }          void SetTextboxTextSafe(int result)         {             label1.Text = result.ToString();         }          private static void SumData(object state)         {             int result;             //int[] icount = (int[])state;             int icount = (int)state;              for (int i = icount; i &gt; 0; i--)             {                 result += i;                 System.Threading.Thread.Sleep(1000);             }             setTextboxText(result);         }          delegate void IntDelegate(int result);          private void button2_Click(object sender, EventArgs e)         {             Application.Exit();         }     } }   Why is this error occurring?     An object reference is required for the nonstatic field, method, or property 'WindowsApplication1.Form1.setTextboxText(int)
24404
Is there any way to determine (programatically, of course) if a given pointer is "valid"? Checking for NULL is easy, but what about things like 0x00001234? When trying to dereference this kind of pointer an exception/crash occurs.  A cross-platform method is preferred, but platform-specific (for Windows and Linux) is also ok.  Update for clarification: The problem is not with stale/freed/uninitialized pointers; instead, I'm implementing an API that takes pointers from the caller (like a pointer to a string, a file handle, etc.). The caller can send (in purpose or by mistake) an invalid value as the pointer. How do I prevent a crash?
87503
I always read that it is recommended to set objects to nothing, once I am done with them. But I normally use them only in functions inside forms.  Isn't the reference lost and memory released when the function scope is left, regardless of setting objects to Nothing?   i.e. is it really necessary to do:  Set db = Nothing Set record_set = Nothing
51720
Is there a way to tell if an event handler has been added to an object?  I'm serializing a list of objects into/out of session state so we can use SQL based session state... When an object in the list has a property changed it needs to be flagged, which the event handler took care of properly before.  However now when the objects are deserialized it isn't getting the event handler.  In an fit of mild annoyance, I just added the event handler to the Get property that accesses the object.  It's getting called now which is great, except that it's getting called like 5 times so I think the handler just keeps getting added every time the object is accessed.  It's really safe enough to just ignore, but I'd rather make it that much cleaner by checking to see if the handler has already been added so I only do so once.  Is that possible?  EDIT: I don't necessarily have full control of what event handlers are added, so just checking for null isn't good enough.
13551
UPDATE   I have combined various answers from here into a 'definitive' answer on a .  Original question  In my code I have an event publisher, which exists for the whole lifetime of the application (here reduced to bare essentials):  public class Publisher {     //ValueEventArgs&lt;T&gt; inherits from EventArgs     public event EventHandler&lt;ValueEventArgs&lt;bool&gt;&gt; EnabledChanged;  }   Because this publisher can be used all over the place, I was quite pleased with myself for creating this little helper class to avoid re-writing the handling code in all subscribers:  public static class Linker {     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged += (s, e) =&gt; subscriber.Enabled = e.Value;     }      //(Non-lambda version, if you're not comfortable with lambdas)     public static void Link(Publisher publisher, Control subscriber)     {          publisher.EnabledChanged +=              delegate(object sender, ValueEventArgs&lt;bool&gt; e)              {                   subscriber.Enabled = e.Value;              };     } }   It worked fine, until we started using it on smaller machines, when I started getting the occasional:  System.ComponentModel.Win32Exception Not enough storage is available to process this command   As it turns out, there is one place in the code where subscribers controls are being dynamically created, added and removed from a form. Given my advanced understanding of garbage collection etc (i.e. none, until yesterday), I never thought to clear up behind me, as in the vast majority of cases, the subscribers also live for the lifetime of the application.  I've fiddled around a while with , but it doesn't work with anonymous delegates (not for me anyway).  Is there anyway out of this problem? I really would like to avoid having to copy-paste boiler-plate code all over the shop.  (Oh, and don't bother with asking me WHY we are creating and destroying controls all the time, it wasn't my design decision...)  (PS: It's a winforms application, but we've upgraded to VS2008 and .Net 3.5, should I consider using the ?)  (PPS: Good , but if anyone can come up with an equivalent to the WeakEventHandler which avoids me having to remember to explicitly UnLink/Dispose, that would be cool...)  EDIT I must admit that I worked around this problem by "recycling" the controls in question. However the workaround has come back to haunt me as the 'key' I was using is apparently non-unique (sob). I've just discovered other links  (tried this - seems to be a bit too weak - GC clears delegates even if target is still alive, same problem with  below),  (forces you to modify publisher, and doesn't really work with anonymous delegates) and  (cited-as-incomplete by Dustin Campbell).   It occurs to me that what I'm looking for may be semantically impossible - closures are designed to 'hang around even after I'm gone'.   I've found another workaround, so I'll stick with that, pending a .
7839
When architecting a solution, I often find myself wanting to know which (of the less-used) standard objects support triggers.    Does anyone know of a single compiled list of standard objects that are not triggerable, for quick reference?  The emphasis here is on quick reference.
75805
After hitting a few StackOverflowExceptions in .NET I noticed they completely bypass the unhandled exception handlers that .NET offers (Application.ThreadException / AppDomain.UnhandledException). This is very disturbing since we have critical cleanup code in those exception handlers.  Is there any way to overcome this?
97823
I'm updating some old Managed C++ code with lines like this:  instanceOfEventSource-&gt;add_OnMyEvent(      new EventSource::MyEventHandlerDelegate(this, MyEventHandlerMethod) );   where   EventSource is the class that publishes events instanceOfEventSource is an instance of that class EventSource::MyEventHandlerDelegate is the delegate type for the event MyEventHandlerMethod is a (non-static) method within the current class (of which "this" is an instance) with the signature matching EventSource::MyEventHandlerDelegate   What is the right syntax for this in C++/CLI?
5432
Can anyone provide a good explanation of the volatile keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking?