Click here to Skip to main content
15,890,043 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I randomly observe this
C#
System.InvalidOperationException: Value Dispose() cannot be called while doing CreateHandle().

exception on click of Winform Close button operation.
On Close button click event, I just close the form by calling form Close function.

I have defined an EventHandler for on Form "Closed" operation. Within the EventHandler I m stopping the Timer and calling Timer.Dispose() function. I define and start this Timer on Form load. The Timer is of type System.Windows.Forms.Timer().

Since this is WinForms Timer I believe this will be executed by UI thread. Before stopping the Timer I also check if its Enabled or not. If its Enabled I will Stop it, else I Dispose it off.

There are multiple Timer of the same type defined within the application. Is it possible that one timer affects the other in any way?.
A NOTE provided in MSDN link Timer.Stop Method (System.Windows.Forms)[^] suggest something like this.


Any help in resolving this exception is appreciated.

Thanks.

What I have tried:

I unsubscribed the Timer.Tick eventhandler, within the form Close and tested the same. But the exception still persists.
Posted
Updated 23-Sep-16 20:13pm
v2
Comments
Philippe Mori 24-Sep-16 13:32pm    
Show us pertinent code... Obviously, if you have such problems, then your code is incorrect but without code, we cannot help you much.
But if you have a timer on a form, then why not drop the timer on the form and let the framework handle the disposing of the timer? You would only need to disable the timer when the form is closing/closed.
Saiprasad V 26-Sep-16 3:27am    
Yes, I am going to remove the Timer.Dispose() from the Form close handler and let garbage collector do the rest. Thank you for your feedback.

1 solution

Don't call Timer.Dispose() on form close, just disable the timer, .net will dispose of the timer with the form when done.
 
Share this answer
 
Comments
Saiprasad V 24-Sep-16 2:20am    
Thanks for the reply. Is it necessary that I still unsubscribe the Timer.Tick eventhandler after stopping?. Asking this since I have multiple timers of same type and only UI thread will execute all the Tick events.
Mehdi Gholam 24-Sep-16 2:34am    
No need to unsubscribe the garbage collector will handle it.
Saiprasad V 24-Sep-16 2:36am    
Thank you. I will try this out

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900