开发者

stop executing code in thread after 30s

开发者 https://www.devze.com 2023-01-14 00:37 出处:网络
how to stop executing code in thread if takes to long. I have few threads which working all the time but after while co开发者_如何转开发de in thread is executing too long and application stop respondi

how to stop executing code in thread if takes to long. I have few threads which working all the time but after while co开发者_如何转开发de in thread is executing too long and application stop responding.

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.

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

精彩评论

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