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