30秒后停止在线程中执行代码 [英] stop executing code in thread after 30s

查看:50
本文介绍了30秒后停止在线程中执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果花很长时间,如何停止在线程中执行代码.我几乎没有什么线程可以一直工作,但是在线程中的代码执行时间过长而应用程序停止响应之后.

how to stop executing code in thread if takes to long. I have few threads which working all the time but after while code in thread is executing too long and application stop responding.

是否有可能如果代码未在30秒钟内执行,则线程将停止执行该代码并转到下一个代码...,因此应用程序仍将处于活动状态并且不会停止响应.我正在使用C#.net 3.5

is it possible that if code is not executed in 30s thread will stop executing it and go to next code... so application will still be alive and will not stop responding. i am using C# .net 3.5

推荐答案

我在这里的答案类似于我发布的答案

My answer here is similar to the one I posted here.

您可以通过在监视线程上等待工作线程达指定的时间,然后强制杀死工作线程(如果尚未完成)来执行此操作.请参见下面的示例代码.

You can do this by waiting on your worker thread from a monitoring thread for a specified amount of time and then forcefully killing the worker thread if it hasn't already completed. See the example code below.

但是,通常,通常使用 Thread.Abort 并不是一个好主意,因为目标线程不一定处于已知状态,并且可能具有无法释放资源的打开句柄.使用 Thread.Abort

In general, however, killing a thread forcefully with Thread.Abort is not a good idea since the target thread is not necessarily in a known state and could have open handles to resources that might not be freed. Using Thread.Abort is a code smell.

更干净的方法是更改​​工作线程以管理自己的生命周期.工作线程可以检查它在众所周知的检查点执行了多长时间,然后在超过某个限制时停止.这种方法的缺点是可能需要在整个线程正在进行的实际工作中散布许多检查点.另外,通过在检查点之间进行过多的计算,工作线程很容易超出限制.

The cleaner way is to change the worker thread to manage its own lifetime. The worker thread could check how long it has executed at well-known checkpoints and then stop if it has exceeded some limit. This approach has the drawback of requiring potentially many checkpoints scattered throughout the actual work the thread is doing. Also, the worker thread could easily exceed a limit by doing too much computation between checkpoints.

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

这篇关于30秒后停止在线程中执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆