I'm a CompSci student, and fairly new at C#, and I was doing a "Josephus Problem" program for a class, and I created an Exit button that calls Application.Exit() to exit at anytime, but if C# is still working on painting and the button is pressed it throws an ObjectDisposedExeception for the Graphics object. Is there any way to prevent this?. I was thinking of try{}catch or change a boolean to tell the painting process to stop before exiting, but I want to know if there's another solution.
C# – How to prevent the ObjectDisposedException in C# when drawing and application exits
c++exception-handlinggraphics
Related Question
- C# – How to create an Excel (.XLS and .XLSX) file in C# without installing Microsoft Office
- C# – the difference between a field and a property
- C# – How to convert a byte array to a hexadecimal string, and vice versa
- C# – How to update the GUI from another thread
- C# – How to get the application’s path in a .NET console application
- C# – How to remedy “The breakpoint will not currently be hit. No symbols have been loaded for this document.” warning
- C# – a NullReferenceException, and how to fix it
- C# – How and when to use ‘async’ and ‘await’
Best Solution
It shouldn't be possible for this to happen. If the button is created on the same thread as the window, they share a message pump and the Paint handler cannot be interrupted to handle the exit button. The message that the button has been clicked will be queued up on the thread's message queue until the Paint handler returns.
Generally, you should defer painting to the Paint handler (or override OnPaint) and everywhere else that you need to update the screen, call the control's Invalidate method. That tells Windows that an area needs repainting and, once all other messages have been dealt with, it will generate a
WM_PAINT
message which ultimately will call OnPaint, which in turn will fire the Paint event.If animating, use a
System.Windows.Forms.Timer
to trigger each frame, rather than using a thread.System.Threading.Timer
callbacks execute on the threadpool, so they're always on the wrong thread for manipulating the UI.