6

スレッドを再起動しようとすると、System.Threading.ThreadStateExceptionが発生することがあります。問題のコードは次のとおりです。

// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{ 
    Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or doesn't exist
if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped)
{ 
    this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); }
// Start the thread
if (check)
{ 
    this.mThread.Start(60000); 
}
else
{   
    this.mThread.Start(0); 
}

それで、2つの質問-これは物事を行う正しい方法ですか、そしてそれは、エラーの発生を防ぐ方法がありますか?

4

3 に答える 3

6

スレッドが一度に複数の状態になる可能性があるため、ThreadStateプロパティは実際には可能な状態のビットマップです。したがって、1つの状態だけで同等性をテストしても、正しい結果は得られません。次のようなことをする必要があります。

if((mThread.ThreadState & ThreadState.Running) != 0)

ただし、スレッドの状態をチェックすることは何もするのに間違っています。何を達成しようとしているのか完全にはわかりませんが、スレッドを再起動する前に、スレッドが終了するのを待っていると思います。その場合は、次のことを行う必要があります。

mThread.Join();
mThread = new Thread(new ParameterizedThreadStart(Monitor));
if(check)
    mThread.Start(60000);
else
    mThread.Start(0);

あなたが解決しようとしている問題をより詳細に説明すれば、私はほぼ確実にもっと良い解決策があるでしょう。スレッドを再起動するためだけにスレッドが終了するのを待つことは、私にはそれほど効率的ではないようです。おそらく、ある種のスレッド間通信が必要ですか?

ジョン。

于 2008-08-16T16:25:07.003 に答える
3

The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the details behind the check variable, it's impossible to know what might trigger this behavior.

You should reorganize your code so that .Start is guaranteed to only be called on new objects. In short, you should put the Start method into the same if-statement as the one that creates a new thread object.

Personally, I would try to reorganize the entire code so that I didn't need to create another thread, but wrap the code inside the thread object inside a loop so that the thread just keeps on going.

于 2008-08-16T17:56:47.147 に答える
1

開始可能な状態ではないスレッドを開始しようとしているため、ThreadStateExceptionがスローされます。最も可能性の高い状況は、すでに実行されているか、完全に終了していることです。

発生する可能性のあることがいくつかある可能性があります。まず、スレッドが実行中からStopRequestedに移行した可能性がありますが、これはまだ完全に停止されていないため、ロジックは新しいスレッドを作成せず、実行を終了したばかりのスレッドを開始しようとしています。実行を終了します(どちらも再起動に有効な状態ではありません)。

もう1つの可能性は、スレッドが中止されたことです。中止されたスレッドは、停止状態ではなく中止状態になります。もちろん、再起動することもできません。

実際、「再起動」できるスレッドはまだ生きている唯一の種類であり、中断されているスレッドです。代わりに、次の条件を使用することをお勧めします。

if (this.mThread == null || this.mThread.ThreadState != ThreadState.Suspended)

于 2008-08-16T16:18:58.060 に答える