C# - Exception handling in ThreadPool.QueueUserWorkItem()

Any uncaught exception on a background thread will immediately terminate your application. This is by design.

The recommended technique for handling exceptions on threads created with ThreadPool.QueueUserWorkItem() is simple.

Surround your code with try/catch. Do not allow exceptions to escape the callback.

using System.Threading;
 
namespace Zuga.net
{
    class Program
    {
        static void Main(string[] args)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), null);
            // ...
        }
 
        private static void ThreadProc(object state)
        {
            try
            {
                // Your code
                throw new Exception("Error");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
    }
}

What happens without try/catch:

[program-has-stopped-working-1.gif]
[program-has-stopped-working-2.gif]

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath