怎么让创建的线程怎么暂停?VS2005提示 线程目前未运行;无法使其挂起

wencai8792 2009-09-26 05:40:12

C#

private void startBtn_Click(object sender, EventArgs e)
{


Thread trd = new Thread(new ThreadStart(this.attackThread));//创建线程
trd.IsBackground = true;
if (startBtn.Text == "开始")
{
timer2.Start();
startBtn.Text = "暂停";
trd.Start();

}
else if (startBtn .Text =="暂停")
{
trd.Suspend();//发VS2005提示 线程目前未运行;无法使其挂起。
startBtn.Text = "开始";
MessageBox.Show("停止动作!");


}
}

请问我错哪了?怎 么修改??谢谢~
...全文
340 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复


System.Threading.Thread trd; //定义全局变量


private void startBtn_Click(object sender, EventArgs e)
{


trd = new Thread(new ThreadStart(this.attackThread));//创建线程
trd.IsBackground = true;
if (startBtn.Text == "开始" && trd.ThreadState==ThreadState.Unstarted)
{
timer2.Start();
startBtn.Text = "暂停";
trd.Start();

}
else if (startBtn .Text =="暂停" && trd.ThreadState==ThreadState.Running)
{
trd.Suspend();//发VS2005提示 线程目前未运行;无法使其挂起。
startBtn.Text = "开始";
MessageBox.Show("停止动作!");


}
}

  • 打赏
  • 举报
回复

System.Threading.Thread th; //定义全局变量


private void startBtn_Click(object sender, EventArgs e)
{


Thread trd = new Thread(new ThreadStart(this.attackThread));//创建线程
trd.IsBackground = true;
if (startBtn.Text == "开始" && trd.ThreadState==ThreadState.Unstarted)
{
timer2.Start();
startBtn.Text = "暂停";
trd.Start();

}
else if (startBtn .Text =="暂停" && trd.ThreadState==ThreadState.Running)
{
trd.Suspend();//发VS2005提示 线程目前未运行;无法使其挂起。
startBtn.Text = "开始";
MessageBox.Show("停止动作!");


}
}

wencai8792 2009-09-26
  • 打赏
  • 举报
回复
是这样的,第一次点按钮,trd.start();//线程正程运行了,线程里是一个do{}while();方法,,
当我第二次点按钮时,我希望线程暂停,,但是还是不行~~
会不会因为第二次点时重新new Thread了呢?

把 Thread trd = new Thread(new ThreadStart(this.attackThread));//创建线程
放到这里面:
if (startBtn.Text == "开始")
{
Thread trd = new Thread(new ThreadStart(this.attackThread));
timer2.Start();
startBtn.Text = "暂停";
trd.Start();

}

又会出现异常 :未将对象引用设置到对象的实例。
wuyq11 2009-09-26
  • 打赏
  • 举报
回复
先要运行,再挂起
Thread thread1 = new Thread(new ThreadStart(Method1));
thread1.Start();
if (thread1.IsAlive )
{
thread1.Suspend();
thread1.Resume();
thread1.Abort();
}
loricheung 2009-09-26
  • 打赏
  • 举报
回复
线程没有开启,你怎么暂停!用IsAlive()判断下再做暂停的动作!
jbo126 2009-09-26
  • 打赏
  • 举报
回复
你那个线程是干什么的,是不是一旦运行就立即停止了,或者你的那个startBtn设计时的Text属性是"暂停"?
CsToD 2009-09-26
  • 打赏
  • 举报
回复
trd你启动了吗?可能是trd已经结束了,所以不能挂起

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧