如何避免线程在等待下或相似的场景(希望让一个线程等待当且仅当它真的真的有必要)? [英] How to avoid thread waiting in the following or similar scenarios (want to make a thread wait iff its really really necessary)?

查看:128
本文介绍了如何避免线程在等待下或相似的场景(希望让一个线程等待当且仅当它真的真的有必要)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参阅下面的code段。我想执行一个长时间运行的任务,但我不希望等待它超过给定超时。我想有任务启动时就完全控制,所以生成一个新的线程,做的工作,只是在等待它的父线程。该模式确实有效,但父线程只是在等待。理想情况下,我不喜欢线程睡眠/等待未扣除其真正需要的。我怎样才能做到这一点?任何建议/想法/模式是值得欢迎的。

Please see the below code snippet. I am trying to execute a long running task, but i dont want to wait it for more than given timeout. I want to have full control on when the task starts, so spawning a new thread and doing the work, and simply waiting for it in parent thread. The pattern really works, but the parent thread is simply waiting. Ideally, i dont like thread to sleep/wait un-less its really needed to. How can i achieve this? any suggestions/thoughts/patterns are welcome.

/// <summary>
/// tries to execute a long running task
/// if the task is not completed in specified time, its deemed un-sccessful.
/// </summary>
/// <param name="timeout"></param>
/// <returns></returns>
bool Task(int timeout)
{
    bool workCompletedSuccessfully = false;
    //I am intentionally spawning thread as i want to have control when the thread start
    //so not using thread pool threads.
    Thread t = new Thread(() =>
    {
        //executes some long running task
        //handles all the error conditions
        //ExecuteTask();
        workCompletedSuccessfully = true;
    });
    t.Start();
    //cannot wait more "timeout"                        
    //My main thread (parent) thread simply waiting for the spawened thread to join
    //HOW CAN I AVOID THIS?ANY PATTERN TO AVOID THIS REALLY HELPS?
    t.Join(timeout);
    if (!workCompletedSuccessfully)
    {
        //deeemed un-successful
        //do the remediation by gracefully disposing the thread
        //itnentionally hidden details about disposing thread etc, to concentrate on 
        //the question - AVOIDING PARENT THREAD TO WAIT
    }
    return workCompletedSuccessfully;
}

问候, 梦想家

Regards, Dreamer

推荐答案

使用的的AutoResetEvent

bool Task(int timeout)
{
    AutoResetEvent threadFinished = new AutoResetEvent(false);
    //I am intentionally spawning thread as i want to have control when the thread start
    //so not using thread pool threads.
    Thread t = new Thread(() =>
    {
        //executes some long running task
        //handles all the error conditions
        //ExecuteTask();
        threadFinished.Set();
    });
    t.Start();
    //Param - timeout
    bool finished = threadFinished.WaitOne(timeout);
    if (!finished)
    {
        //deeemed un-successful
        //do the remediation by gracefully disposing the thread
    }
    return finished;
}

我在这里看到的唯一的问题是,你打算做什么用线程没有按时完成。从理论上讲,你可以拨打 Thread.Abort的()但它不是好主意,因为它可以应用损坏状态。

The only problem I see here is what you plan to do with thread that didn't finish on time. Theoretically you can call Thread.Abort() but it is not good idea, because it can corrupt state of application.

修改:你要明白, threadFinished.WaitOne(超时); 仍然阻挡,但不应大于超时

Edit: You need to understand that threadFinished.WaitOne(timeout); is still blocking, but not longer then timeout.

这篇关于如何避免线程在等待下或相似的场景(希望让一个线程等待当且仅当它真的真的有必要)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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