C # Thread Exception Handling

I thought I understood this, and I’m a little awkward to ask, but can someone explain to me why the breakpoint in the exception handler from the following code did 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);
        }
    }
+5
source share
5 answers

You create a thread, set it as a background thread, and start it. Your "main" thread ends. Since the new thread is a background thread, it does not remain operational - so the whole process ends before the background thread encounters any problems.

If you write:

testThread.Join();

in your method Mainor do not set the new thread as a background thread, you must click a breakpoint.

+11

- ( ). , , , .

main , , .

testThread.Join(), , .

+1

, Main - . , , Main .

- . . .

0

Since the new thread IsBackgroundis true, it will not prevent the completion of the process. At the end Main(), only the front thread is completed, ending the process before another thread reaches this.

0
source

Probably because the main thread ends before the worker thread. Try to add

Console.ReadKey();

at the end of your method Main.

0
source

All Articles