<p>In a VB.NET WinForms project, I get an exception</p>

<blockquote>
  <p>Cannot access a disposed of object</p>
</blockquote>

<p>when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:</p>

<pre><code>Cannot access a disposed object. Object name: 'dbiSchedule'.
  at System.Windows.Forms.Control.CreateHandle()
  at System.Windows.Forms.Control.get_Handle()
  at System.Windows.Forms.Control.PointToScreen(Point p)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0)
  at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1)
  at System.Windows.Forms.Timer.OnTick(EventArgs e)
  at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message&amp; m)
  at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
</code></pre>

<p>The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.</p>

<p>Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?</p>

<hr>

<p>Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.</p>

<p>It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.</p>

[{'answer_id': 29634, 'author': 'jfs', 'author_id': 718, 'author_profile': 'https://Stackoverflow.com/users/718', 'pm_score': 5, 'selected': False, 'text': '<p>Try checking the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isdisposed.aspx" rel="noreferrer">IsDisposed</a> property before accessing the control. You can also check it on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx" rel="noreferrer">FormClosing</a> event, assuming you\'re using the FormClosed event.</p>\n\n<blockquote>\n  <p>We do stop the Timer on the\n  FormClosing event and we do check the\n  IsDisposed property on the schedule\n  component before using it in the Timer\n  Tick event but it doesn\'t help.</p>\n</blockquote>\n\n<p>Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "<a href="http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx" rel="noreferrer">When to call GC.Collect()</a>".</p>\n'}, {'answer_id': 29635, 'author': 'imaginaryboy', 'author_id': 2508, 'author_profile': 'https://Stackoverflow.com/users/2508', 'pm_score': 1, 'selected': False, 'text': "<p>You sure the timer isn't outliving the 'dbiSchedule' somehow and firing after the 'dbiSchedule' has been been disposed of?</p>\n\n<p>If that is the case you might be able to recreate it more consistently if the timer fires more quickly thus increasing the chances of you closing the Form just as the timer is firing.</p>\n"}, {'answer_id': 29636, 'author': 'On Freund', 'author_id': 2150, 'author_profile': 'https://Stackoverflow.com/users/2150', 'pm_score': 0, 'selected': False, 'text': "<p>Looking at the error stack trace, it seems your timer is still active. Try to cancel the timer upon closing the form (<em>i.e.</em> in the form's OnClose() method). This looks like the cleanest solution.</p>\n"}, {'answer_id': 29637, 'author': 'Gishu', 'author_id': 1695, 'author_profile': 'https://Stackoverflow.com/users/1695', 'pm_score': 4, 'selected': False, 'text': "<p>It looks like a threading issue.<br>\n<strong>Hypothesis</strong>: Maybe you have the main thread and a timer thread accessing this control. The main thread shuts down - calling Control.Dispose() to indicate that I'm done with this Control and I shall make no more calls to this. However, the timer thread is still active - a context switch to that thread, where it may call methods on the same control. Now the control says I'm Disposed (already given up my resources) and I shall not work anymore. ObjectDisposed exception.</p>\n\n<p><strong>How to solve this</strong>: In the timer thread, before calling methods/properties on the control, do a check with </p>\n\n<pre><code>if ControlObject.IsDisposed then return; // or do whatever - but don't call control methods\n</code></pre>\n\n<p>OR stop the timer thread BEFORE disposing the object.</p>\n"}, {'answer_id': 29646, 'author': 'samjudson', 'author_id': 1908, 'author_profile': 'https://Stackoverflow.com/users/1908', 'pm_score': 1, 'selected': False, 'text': '<p>Another place you could stop the timer is the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx" rel="nofollow noreferrer">FormClosing</a> event - this happens before the form is actually closed, so is a good place to stop things before they might access unavailable resources.</p>\n'}, {'answer_id': 29747, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 2, 'selected': False, 'text': "<blockquote>\n  <p>we do check the IsDisposed property on\n  the schedule component before using it\n  in the Timer Tick event but it doesn't\n  help.</p>\n</blockquote>\n\n<p>If I understand that stack trace, it's not your timer which is the problem, it's one in the control itself - it might be them who are not cleaning-up properly.</p>\n\n<p>Are you explicitly calling Dispose on their control?</p>\n"}, {'answer_id': 48599, 'author': 'Garo Yeriazarian', 'author_id': 2655, 'author_profile': 'https://Stackoverflow.com/users/2655', 'pm_score': 2, 'selected': False, 'text': "<p>Stopping the timer doesn't mean that it won't be called again, depending on when you stop the timer, the timer_tick may still be queued on the message loop for the form.  What will happen is that you'll get one more tick that you may not be expecting.  What you can do is in your timer_tick, check the Enabled property of your timer before executing the Timer_Tick method.</p>\n"}, {'answer_id': 444024, 'author': 'Steve J', 'author_id': 50568, 'author_profile': 'https://Stackoverflow.com/users/50568', 'pm_score': 1, 'selected': False, 'text': "<p>If this happens sporadically then my guess is that it has something to do with the timer.</p>\n\n<p>I'm guessing (and this is only a guess since I have no access to your code) that the timer is firing while the form is being closed.  The dbiSchedule object has been disposed but the timer somehow still manages to try to call it.  This <em>shouldn't</em> happen, because if the timer has a reference to the schedule object then the garbage collector should see this and not dispose of it.</p>\n\n<p>This leads me to ask: are you calling Dispose() on the schedule object manually?  If so, are you doing that before disposing of the timer?  Be sure that you release all references to the schedule object before Disposing it (i.e. dispose of the timer beforehand).</p>\n\n<p>Now I realize that a few months have passed between the time you posted this and when I am answering, so hopefully, you have resolved this issue.  I'm writing this for the benefit of others who may come along later with a similar issue.</p>\n\n<p>Hope this helps.</p>\n"}, {'answer_id': 9232678, 'author': 'goku_da_master', 'author_id': 151325, 'author_profile': 'https://Stackoverflow.com/users/151325', 'pm_score': 2, 'selected': False, 'text': "<p>I had the same problem and solved it using a boolean flag that gets set when the form is closing (the System.Timers.Timer does not have an IsDisposed property).  Everywhere on the form I was starting the timer, I had it check this flag.  If it was set, then don't start the timer.  Here's the reason:</p>\n\n<p><strong>The Reason:</strong></p>\n\n<p>I was stopping and disposing of the timer in the form closing event.  I was starting the timer in the Timer_Elapsed() event.  If I were to close the form in the middle of the Timer_Elapsed() event, the timer would immediately get disposed by the Form_Closing() event.  This would happen before the Timer_Elapsed() event would finish and more importantly, before it got to this line of code:</p>\n\n<pre><code>_timer.Start()\n</code></pre>\n\n<p>As soon as that line was executed an ObjectDisposedException() would get thrown with the error you mentioned.</p>\n\n<p><strong>The Solution:</strong></p>\n\n<pre><code>Private Sub myForm_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing\n    ' set the form closing flag so the timer doesn't fire even after the form is closed.\n    _formIsClosing = True\n    _timer.Stop()\n    _timer.Dispose()\nEnd Sub\n</code></pre>\n\n<p>Here's the timer elapsed event:</p>\n\n<pre><code>Private Sub Timer_Elapsed(ByVal sender As System.Object, ByVal e As System.Timers.ElapsedEventArgs) Handles _timer.Elapsed\n    ' Don't want the timer stepping on itself (ie. the time interval elapses before the first call is done processing)\n    _timer.Stop()\n\n    ' do work here\n\n    ' Only start the timer if the form is open. Without this check, the timer will run even if the form is closed.\n    If Not _formIsClosing Then\n        _timer.Interval = _refreshInterval\n        _timer.Start() ' ObjectDisposedException() is thrown here unless you check the _formIsClosing flag.\n    End If\nEnd Sub\n</code></pre>\n\n<p>The interesting thing to know, even though it would throw the ObjectDisposedException when attempting to start the timer, the timer would still get started causing it to run even when the form was closed (the thread would only stop when the application was closed).</p>\n"}, {'answer_id': 9684775, 'author': 'PUG', 'author_id': 384554, 'author_profile': 'https://Stackoverflow.com/users/384554', 'pm_score': 0, 'selected': False, 'text': '<p>My Solution was to put a try catch, &amp; is working fine</p>\n\n<blockquote>\n  <p>try  {<br>\n  this.Invoke(new EventHandler(DoUpdate));\n    }<br>catch  {  }</p>\n</blockquote>\n'}, {'answer_id': 49817046, 'author': 'Yasin Ugurlu', 'author_id': 7300935, 'author_profile': 'https://Stackoverflow.com/users/7300935', 'pm_score': -1, 'selected': False, 'text': '<p>because the solution folder was inside OneDrive folder.</p>\n\n<p>If you moving the solution folders out of the one drive folder made the errors go away.</p>\n\n<p>best</p>\n'}]
['https://Stackoverflow.com/questions/29626', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/961/']