1

请看下面的代码片段。我正在尝试执行一个长时间运行的任务,但我不想等待超过给定的超时时间。我想完全控制任务何时开始,因此产生一个新线程并完成工作,并在父线程中等待它。该模式确实有效,但父线程只是在等待。理想情况下,我不喜欢线程休眠/等待,除非它真的需要。我怎样才能做到这一点?欢迎任何建议/想法/模式。

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

问候,梦想家

4

1 回答 1

2

使用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(),但这不是一个好主意,因为它会破坏应用程序的状态。

编辑:您需要了解threadFinished.WaitOne(timeout);仍然阻塞,但不再阻塞timeout

于 2013-03-10T00:24:30.977 回答