终止System.Timers.Timer线程

xiaozhunamen 2014-05-05 09:12:30
点击Button1运行后,点击Button2.但是计时器里面的While循环体还在执行,怎样结束此线程?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


System.Timers.Timer t = new System.Timers.Timer(1000);
private void Form1_Load(object sender, EventArgs e)
{
t.Elapsed += new System.Timers.ElapsedEventHandler(t_Elapsed);
}

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
t.Stop();
int n = 0;
while (true)
{
n++;
System.Threading.Thread.Sleep(1000);
this.label1.Text = n.ToString();
}
}
private void bgwTest_DoWork(object sender, DoWorkEventArgs e)
{

if (bgwTest.CancellationPending)
{
e.Cancel = true;
}

t.Start();
}

private void bgwTest_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//MessageBox.Show("OK");
}

private void button1_Click(object sender, EventArgs e)
{
if (bgwTest.IsBusy)
{
bgwTest.CancelAsync();
}

t.Stop();
bgwTest.RunWorkerAsync();
}

private void button2_Click(object sender, EventArgs e)
{
t.Enabled = false;
t.Stop();
}
}
}
...全文
246 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
於黾 2014-05-05
  • 打赏
  • 举报
回复
另外,timer本身就是每间隔固定时间就执行一次的,你里面套while有什么必要么?
於黾 2014-05-05
  • 打赏
  • 举报
回复
引用 3 楼 xiaozhunamen 的回复:
已经在执行的代码是不会停下来的 现在就是要解决这个问题的,已经执行的代码怎样终止?
while(timer1.enable) 这样timer1不可用的时候就退出循环了 不要用死循环
xiaozhunamen 2014-05-05
  • 打赏
  • 举报
回复
已经在执行的代码是不会停下来的 现在就是要解决这个问题的,已经执行的代码怎样终止?
於黾 2014-05-05
  • 打赏
  • 举报
回复
t.stop()或t.enable=false 仅仅是timer不会被时间触发,已经在执行的代码是不会停下来的 里面不要有死循环
於黾 2014-05-05
  • 打赏
  • 举报
回复
timer的代码在哪呢? 另外,timer本身就是定时执行的,怎么里面还有while?

110,526

社区成员

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

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

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