标签:
using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace TestApplication1 { public partial class Form2 : Form { delegate void CountEventHandler(object sender, int count); CancellationTokenSource tokenSource; CancellationToken token; public Form2() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { tokenSource = new CancellationTokenSource(); token = tokenSource.Token; Task.Factory.StartNew(Run, token); } void Run() { long rCount = Convert.ToInt64(textBox1.Text); for (int i = 0; i < rCount; i++) { CountChange(null, i); } } private void CountChange(object sender, int i) { if (token.IsCancellationRequested) return; if (textBox2.InvokeRequired) { textBox2.Invoke(new CountEventHandler(CountChange), sender, i); } else { textBox2.Text = i.ToString(); } } private void button2_Click(object sender, EventArgs e) { tokenSource.Cancel(); } } }
button1 > 启动 button2 > 停止 textBox1 > 总循环次数 textBox2 > 当前计数
标签:
原文地址:http://www.cnblogs.com/z5337/p/5684128.html