在.net4.5之后,线程的使用有了新的方法task,也是微软极力推荐的一种方法,可以做到线程池threadpool的管理,两个线程互不干扰,连跨线程操作的invoke都省略掉了,如果有返回值,就要在返回类型上加上 Task<>,比如:Task<string>。在调用时要加上 await。由于内部有 await,就必须用 async 标记。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApp3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SetValue();
}
//private void SetValue()
//{
// Task.Run(() => {
// Thread.Sleep(2000); // 模拟大量工作阻塞 2 秒
// button1.Text = "1";
// });
//}
int x = 0;
int y = 0;
private async void SetValue()
{
while (true)
{
textBox1.Text = await GetValue();
}
}
private Task<string> GetValue()
{
x++;
return Task.Run(() =>
{
Thread.Sleep(100); // 模拟大量工作阻塞 2 秒
return x.ToString ();
});
}
private void button2_Click(object sender, EventArgs e)
{
SetValue2();
}
private async void SetValue2()
{
while (true)
{
textBox2.Text = await GetValue2();
}
}
private Task<string> GetValue2()
{
CancellationTokenSource source = new CancellationTokenSource();
//注册任务取消的事件
source.Token.Register(() =>
{
Console.WriteLine("任务被取消后执行xx操作!");
});
y++;
return Task.Run(() =>
{
Thread.Sleep(200); // 模拟大量工作阻塞 2 秒
return y.ToString();
});
//延时取消,效果等同于Thread.Sleep(5000);source.Cancel();
source.CancelAfter(5000);
}
private void button3_Click(object sender, EventArgs e)
{
Task.Run(() =>
{
Action<int> setValue = (i) => { textBox3.Text = i.ToString(); };
for (int i = 0; i < 1000000; i++)
{
Thread.Sleep(100);
textBox3.Invoke(setValue, i);
}
});
}
}
}