Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET C# Thread exception handling

I thought I understood this, and am a bit embarrassed to be asking, but, can someone explain to me why the breakpoint in the exception handler of following code is not hit?

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    static void Main()
    {
        Thread testThread = new Thread(new ParameterizedThreadStart(TestDownloadThread));
        testThread.IsBackground = true;
        testThread.Start();
    }

    static void TestDownloadThread(object parameters)
    {
        WebClient webClient = new WebClient();

        try
        {
            webClient.DownloadFile("foo", "bar");
        }
        catch (Exception e)
        {
            System.Console.WriteLine("Error downloading: " + e.Message);
        }
    }
like image 669
Doo Dah Avatar asked Mar 21 '11 15:03

Doo Dah


1 Answers

You're creating a thread, setting it to be a background thread, and starting it. Your "main" thread is then finishing. Because the new thread is a background thread, it doesn't keep the process alive - so the whole process is finishing before the background thread runs into any problems.

If you write:

testThread.Join();

in your Main method, or don't set the new thread to be a background thread, you should hit the breakpoint.

like image 183
Jon Skeet Avatar answered Oct 22 '22 14:10

Jon Skeet