.net thread monitoring

后端 未结 2 1702
难免孤独
难免孤独 2021-01-06 04:54

I want to monitor one thread from another thread.currently looking at threasd.isalive property. If there is any exception in thread still thread.isalive property is true.

2条回答
  •  渐次进展
    2021-01-06 05:10

    It sounds like the monitored thread is catching the exception it's throwing, otherwise, it would terminate and probably take your entire process down as well. You can subscribe to the AppDomain.FirstChanceException event to figure out when an exception is initially thrown, but even if that happens, you don't necessarily want to kill the thread (what if the thread catches the exception, handles it, and proceeds normally?). Instead, consider letting the exception terminate the thread "normally", and then catch it in your monitor code to prevent it from taking down the process.

    There's no way to tell if a thread is in an infinite loop, but you can kill a thread that's been running for too long (see example code below). Terminating a thread forcefully with Thread.Abort, however, can cause issues and is a code smell (see here). You should consider changing the worker thread to manage its own lifetime.

    class Program
    {
        static void Main(string[] args)
        {
            if (RunWithTimeout(LongRunningOperation, TimeSpan.FromMilliseconds(3000)))
            {
                Console.WriteLine("Worker thread finished.");
            }
            else
            {
                Console.WriteLine("Worker thread was aborted.");
            }
        }
    
        static bool RunWithTimeout(ThreadStart threadStart, TimeSpan timeout)
        {
            Thread workerThread = new Thread(threadStart);
    
            workerThread.Start();
    
            bool finished = workerThread.Join(timeout);
            if (!finished)
                workerThread.Abort();
    
            return finished;
        }
    
        static void LongRunningOperation()
        {
            Thread.Sleep(5000);
        }
    }
    

提交回复
热议问题