Having trouble with background threads and exceptions

G

Guest

Hey guys,

Here is the scenario:

I have the main form open and a background thread is running. The
background thread sometimes needs access to the main forms graphics object
and gets it by calling Graphics g = CreateGraphics().

Now, I close my main form while the background thread is running and when
the background thread gets to the CreateGraphics() line, it throws an
exception (since the main form has been disposed).

I couldn't think of any way to prevent that exception from occuring. Since I
need the forms graphics object to use in that background thread, and checking
if(!this.IsDisposed) isn't guaranteed to always work, I thought I can at
least log the exception. However, that doesn't seem to work either.

The background thread method is enclosed in a try..catch block and in the
catch block I have:

using (StreamWriter sw = new StreamWriter(@"C:\Errors\Log.txt"))
{
sw.WriteLine(DateTime.Now + " [ERROR] " + ex_.Message);
}

When I'm debugging, if I close my main form and, if the exception is thrown,
which is not always, break on the WriteLine I can see the error message fine.
However, after the app closes, the file "Log.txt" is created but is empty.

Does any one have any ideas as to why? I also tried displaying a MessageBox
with the error info but as far as I can tell, either the MessageBox doesn't
appear or flashes quickly and disappears.

Thanks alot,
-Flack
 
W

wfairl

First, how about (!this.IsDisposed && this.Visible)
Second, have you tried explicitly flushing/closing the streamwriter?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top