尝试重新启动一个线程当A ThreadStateException occures [英] A ThreadStateException occures when trying to restart a thread

查看:287
本文介绍了尝试重新启动一个线程当A ThreadStateException occures的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

随着时间的时候,我试图重新启动一个线程,当得到一个System.Threading.ThreadStateException。在code的问题如下:

From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:

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

于是两个问题 - 这是做事的正确方法,是,是有办法prevent发生错误

So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?

推荐答案

现在的问题是,你有C,它首先检查$ C $是否应该创建一个新的线程对象,而另一块code,确定羯羊要启动线程对象。由于竞争条件和类似的东西,你的code可能最终会试图调用。启动现有的线程对象。考虑到你不张贴背后的细节中的检查的变量,这是不可能知道什么可能触发这种行为。

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.

您应该重新组织你的code这样。开始是保证只能被称为新的对象。总之,你应该把启动方式到同一个if语句为创建一个新的线程对象之一。

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.

就个人而言,我会尝试重组整个code,使我并不需要创建另一个线程,但包装线程对象内部的code一个循环中,使线只是不断去

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.

这篇关于尝试重新启动一个线程当A ThreadStateException occures的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆