终止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();
}
}
}
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();
}
}
}
...全文
相关推荐
C# 三种计时器
##### 创建实例```csharpSystem.Timers.Timer timer = new System.Timers.Timer();```##### 设置时间间隔```csharptimer.Interval
C#线程控制
**Timer组件**: - **System.Timers.Timer**:适用于多线程环境,触发事件时在单独的线程上运行。
C#电脑计时器
除了System.Timers.Timer,C#还有System.Windows.Forms.Timer和System.Threading.Timer可供选择。
C#简易计时器
一、基础知识在C#中,我们通常使用System.Timers.Timer类或System.Windows.Forms.Timer类来实现计时器功能。
C#中的多线程
**计时器(Timers)**: 定时器(Timer)提供了一种在指定时间间隔后执行回调的方法。计时器对于周期性的任务调度非常有用。15.


