终止System.Timers.Timer线程
点击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();
}
}
}