using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; using System.Threading.Tasks; namespace WindowsFormsApplication2 { delegate void invokeDelegate(); public partial class Form1 : Form { CancellationTokenSource ts = new CancellationTokenSource(); public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "AAA"); var invokeThread = new Thread(new ThreadStart(StartMethod)); invokeThread.Start(); string a = string.Empty; for (int i = 0; i < 5; i++) //调整循环次数,看的会更清楚 { Thread.Sleep(1000); a = a + "B"; } MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + a); } private void StartMethod() { MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "CCC"); button1.Invoke(new invokeDelegate(invokeMethod)); MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "DDD"); } private void invokeMethod() { Thread.Sleep(3000); MessageBox.Show(Thread.CurrentThread.GetHashCode().ToString() + "EEE"); } private void lableeeidt(string text) { if (label1.InvokeRequired) { label1.Invoke(new Action<string>(lableeeidt),text); } label1.Text = text; } private void Form1_Load(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { Task task = new Task(() => { int i=0; while (!ts.IsCancellationRequested) { i++; lableeeidt(i.ToString()); Thread.Sleep(1000); } },ts.Token); task.Start(); //新开一个task任务,里面用sleep实现超时 Task.Factory.StartNew(() => { Thread.Sleep(4500); ts.Cancel(); }); } } }
在.Net 4.5中,该操作得到了进一步的简化,我们可以通过在创建CancellationTokenSource时设置超时来实现这一功能。
var cancelTokenSource = newCancellationTokenSource(3000);
除此之外,也可以通过如下代码实现同样的效果。
cancelTokenSource.CancelAfter(3000);