终止System.Timers.Timer线程

xiaozhunamen xiaozhunamen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
点击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();
}
}
}
...全文
评论 5
收藏 已收藏
分享
返回顶部
xiaozhunamen
C# 111,129 成员 642,538 内容