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 に答える