Doo Dah
Doo Dah

Reputation: 4029

.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);
        }
    }

Upvotes: 5

Views: 2225

Answers (5)

steinar
steinar

Reputation: 9653

Probably because the main thread is ending before the worker thread. Try adding

Console.ReadKey();

at the end of your Main method.

Upvotes: 0

Jon Hanna
Jon Hanna

Reputation: 113232

Since the new thread's IsBackground is true, it won't prevent the process from terminating. At the end of Main() the only foreground thread terminates, shutting down the process before the other thread gets that far.

Upvotes: 0

Dan Puzey
Dan Puzey

Reputation: 34200

Your thread is a Background thread (you set it so yourself). This means that when the application completes, the thread will be shut down without being given chance to complete.

Because your main has no further content, it exits immediately and both the application and your thread are terminated.

If you were to add a testThread.Join() call then your thread would complete before the app exited and you'd see the exception caught.

Upvotes: 1

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

Most likely your background thread isn't started before Main exits - starting a new thread may take a while. Since the additional thread is a background thread it is terminated when Main exits.

For demo purposes, you could have your main method wait - e.g. on user input. This would allow the background thread to start running.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499730

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.

Upvotes: 11

Related Questions