当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Exception Thrown in thread pool

问题描述:

I have a thread pool and I use a library that if certain conditions are met to throw an exception. My question is if this runs out of the IDE, will the thread come to an halt or will the whole entire program come to a halt?

网友答案:

If the application is .Net 2+, an unhandled exception on a non-main thread will flatten the process.

You can configure this behavior using the app.config LegacyUnhandledExceptionPolicy setting, but I wouldn't recommend this as it potentially masks serious bugs.

Update

If you wish to ignore the occasional timeout exception, consider placing your WebService call in a try\catch block and ignore the timeout exception:

try
{
    //Call WebService
}
catch(System.Net.WebException ex)
{
   //Ignore
}
网友答案:

So lets review what you have:

  • You have a method executing on a TheadPool thread.
  • This method will throw an exception.
  • The exception will not be handled by a try-catch block.
  • The application is running outside of the IDE.

Now we can easily test this with the following code. Pay careful attention to the observations below, especially the bold one, because they are interesting in the context of your question.

public static void Main()
{
    ThreadPool.QueueUserWorkItem(
        (state) =>
        {
            throw new InvalidOperationException();
        }, null);

    while (true)
    {
       Thread.Sleep(1000);
       Console.WriteLine(DateTime.Now.ToString());
    }
}

When running outside of the IDE you will observe the following.

  • A dialog box will appear saying "[application] has encountered a problem and needs to close. We are sorry for the inconvenience."
  • The application will continue to run and print the current time each second.
  • The application will terminate after clicking Close on the dialog box.

When running inside the IDE1 you will observe the following.

  • The IDE will intercept the exception and display it using its own unhandled exception window.
  • All threads will be halted which means you will not see the current time being displayed.
  • Ignoring the exception and resuming the debugging session will allow the current time to begin displaying.
  • The IDE will again rethrow the exception and intercept it.
  • All threads will be halted and the cycle will repeat indefinitely.

1I tested this with Visual Studio 2010.

网友答案:

When the debugger breaks a program, all threads come to a halt.

In the Debug -> Windows -> Threads screen, you can see the threads. You can "freeze" a thread, which means it will stay halted if you continue running the program.

So it is possible to keep some threads halted even when the debugger runs. The opposite is not possible: no thread can run when the debugger is in break mode.

分享给朋友:
您可能感兴趣的文章:
随机阅读: