如何避免线程等待在以下或类似的情况下(想让一个线程等待,如果它真的真的是必要的)

本文关键字:等待 线程 如果 一个 何避免 真的真的 情况下 | 更新日期: 2023-09-27 18:03:20

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

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

问候,做梦的人

如何避免线程等待在以下或类似的情况下(想让一个线程等待,如果它真的真的是必要的)

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

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