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.
Share
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_PAINTmessage which ultimately will call OnPaint, which in turn will fire the Paint event.If animating, use a
System.Windows.Forms.Timerto trigger each frame, rather than using a thread.System.Threading.Timercallbacks execute on the threadpool, so they’re always on the wrong thread for manipulating the UI.