我现在写了一个定时器 每隔一分钟 调用Entrance()方法启动线程 这样线程应该在那里结束? 是否在SendThreadProc和ReceiveThreadProc中 应该怎样写 (第二次调用的时候会出错:(XX线程正在终止))PS:不能用While()来延期执行
public void Entrance()
{
this.sendThread = new Thread(new ThreadStart(SendThreadProc));
sendThread.Name = "Send Thread";
sendThread.Start(); this.receiveThread = new Thread(new ThreadStart(ReceiveThreadProc));
receiveThread.Name = "Receive Thread";
receiveThread.Start();
}
public void Entrance()
{
this.sendThread = new Thread(new ThreadStart(SendThreadProc));
sendThread.Name = "Send Thread";
sendThread.Start(); this.receiveThread = new Thread(new ThreadStart(ReceiveThreadProc));
receiveThread.Name = "Receive Thread";
receiveThread.Start();
}
所以楼主不必担心线程的结束问题,只要你给它的方法执行返回后,自然就结束了。
while(!_shouldStop)
{
//do something
Thread.Sleep(100);
}
{
while()
{
this.sendThread = new Thread(new ThreadStart(SendThreadProc));
sendThread.Name = "Send Thread";
sendThread.Start(); this.receiveThread = new Thread(new ThreadStart(ReceiveThreadProc));
receiveThread.Name = "Receive Thread";
receiveThread.Start();
Thread。Sleep(XX);
}
}
和ReceiveThreadProc两个方法里面设置一个状态值,返回时置为True,然后在这个管理线程的方法里通过判断这个状态值来决定是否启动新的线程
但注意这会引发ThreadAbortException异常,如果就是强行终止线程的话,加上try...catch无视这个Exception
public void Entrance()
{
if(this.sendThread != null)
{
try
{ this.sendThread.Abort(); }
catch
{}
}
this.sendThread = new Thread(new ThreadStart(SendThreadProc));
sendThread.Name = "Send Thread";
sendThread.Start(); ...
}
用 Thread.Join(等待时间)private int checkCount = 0;//Entrance实际是每分钟调用一次的检查线程:
public void Entrance()
{
//如果线程不存在则退出
if(sendThread == null)
return; //等待1秒,判断是否结束
if(sendThread.Join(1000))
{
RestartThread();
}
else
{
checkCount++;
} //如果count大于3次,说明线程已经有3分钟以上没有响应了。
if(checkCount > 3)
{
//那么强制干掉,重启线程
try
{
sendThread.Abort();
}
catch
{}
checkCount = 0;
RestartThread();
}
}private void RestartThread()
{
this.sendThread = new Thread(new ThreadStart(SendThreadProc));
sendThread.Name = "Send Thread";
sendThread.Start(); this.receiveThread = new Thread(new ThreadStart(ReceiveThreadProc));
receiveThread.Name = "Receive Thread";
receiveThread.Start();
}
if(sendThread.Join(1000))
{
//重启线程之前要把count清零
checkCount = 0;
RestartThread();
return;
这个一直判断是空
去掉行不
加上创建的代码就OK了。
if(sendThread == null)
{
RestartThread();
}count用于控制线程的生命 1:就是1分钟,2:就是2分钟
看你要线程活多久重新创建。或者说你程序如何设计线程的工作。
是短期工作然后必需重启呢?还是长期工作需要判断启动正常?如果只是数据库连接不上要重新创建,不应该用这种方式。