开发者

.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(开发者_StackOverflow中文版);

        try
        {
            webClient.DownloadFile("foo", "bar");
        }
        catch (Exception e)
        {
            System.Console.WriteLine("Error downloading: " + e.Message);
        }
    }


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.


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.


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.


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.


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

Console.ReadKey();

at the end of your Main method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜