.NET线程监控线程、NET

2023-09-04 00:48:43 作者:心也会游荡人也会死亡

我要监控从另一个线程thread.currently看着threasd.isalive财产。如果在线程任何异常仍thread.isalive属性为true。

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.

我要杀死线程,如果有螺纹或任何异常,如果线程处于无限循环。

I want to kill thread if there is any exception in thread or if the thread is in infinite loop..

请问AP preacite您的输入/解决方案/建议。

Would appreacite for your inputs/solutions/suggestions.

拉​​朱

推荐答案

这听起来像监视线程捕获异常它抛出,否则将终止,可能把你的整个过程下来为好。您可以订阅 AppDomain.FirstChanceException 事件,找出异常时最初抛出,但即使是这样,你不一定想杀死线程(如果线程捕获异常,处理它,并正常进行?) 。相反,考虑让异常终止线程正常,然后从取下来的过程中您的显示器code赶上它prevent吧。

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.

有没有办法判断一个线程是一个无限循环,但你可以杀死一个已经运行的时间过长(见下面的例子code)的线程。强行终止线程与 Thread.Abort的,但是,可能会导致的问题,是一个code气味(见这里)。你应该考虑改变工作线程来管理自己的生命周期。

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);
    }
}