以下のコード スニペットを参照してください。長時間実行されるタスクを実行しようとしていますが、指定されたタイムアウト以上待ちたくありません。タスクの開始時期を完全に制御したいので、新しいスレッドを生成して作業を行い、親スレッドでそれを待つだけです。パターンは実際に機能しますが、親スレッドは単に待機しています。理想的には、本当に必要でない限り、スレッドがスリープ/待機するのは好きではありません。どうすればこれを達成できますか? 提案/考え/パターンは大歓迎です。
/// <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;
}
よろしく、ドリーマー