开发者

Catching Exceptions in a .NET Thread

How c开发者_StackOverflowould you find out that an Exception occurred in a Thread in a MultiThreaded Application ? and consecutively clean the resources ?

Because otherwise the Thread can be still remaining in memory and running.


As Sean has said, you have to do all exception handling and cleanup inside the thread method, you can't do it in the Thread initialization. For example:

public void Run()
{
    try
    {
        Thread thread1 = new Thread(ThreadEntry1);
        thread1.Start();

        Thread thread2 = new Thread(ThreadEntry2);
        thread2.Start();
    }
    catch (NotImplementedException)
    {
        // Neither are caught here
        Console.WriteLine("Caught you");
    }
}

private void ThreadEntry1()
{
    throw new NotImplementedException("Oops");
}

private void ThreadEntry2()
{
    throw new NotImplementedException("Oops2");
}

Instead, this approach is more self-contained and obviously also works:

public void Run()
{
    Thread thread1 = new Thread(ThreadEntry1);
    thread1.Start();
}

private void ThreadEntry1()
{
    try
    {
        throw new NotImplementedException("Oops");
    }
    catch (NotImplementedException)
    {
        Console.WriteLine("Ha! Caught you");
    }
}

If you want to know if the Thread has failed, then you should consider an array of WaitHandles, and signal back to your calling method. An alternative and simpler approach is to simply increment a counter each time a thread's operation finishes:

Interlocked.Increment(ref _mycounter);


If you're worried about this sort of thing then you should wrap your threads entry point in a try/catch block and do the cleanup explicitly. Any exception passing out of the thread entry point will cause your app to shut down.


A. You have a call stack, and you can catch it inside the thread and add the thread id to the log I guess...

If you wrap your thread in a good manner, you can add cleaing code to the catch section, terminating the thread if needed.


You can catch exceptions within threads like you would any normal function. If your "work" function for a thread is called DoWork then do something like this:

private void DoWork(...args...)
{
try
{
// Do my thread work here
}
catch (Exception ex)
{
}
}


Eric Lippert has a recent post on the badness of exceptions occurring in worker threads. It's worth reading and understanding that an exception is "exceptional" and the only thing that you can be sure of after an exception in a worker thread is that you can no longer be sure of the state of your application.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜