多线程
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 多线程 { public partial class Form1 : Form { private CancellationTokenSource cts; public Form1() { InitializeComponent(); } private void CountTo(int countTo, CancellationToken ct) { int sum = 0; for (; countTo > 0; countTo--) { if (ct.IsCancellationRequested) { break; } sum += countTo; //Invoke方法用于获得创建lbl_Status的线程所在的上下文 this.Invoke(new Action(() => textBox1.Text = sum.ToString())); Thread.Sleep(200); } } private void button1_Click(object sender, EventArgs e) { cts = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(state => CountTo(int.Parse(textBox2.Text), cts.Token)); } private void button2_Click(object sender, EventArgs e) { if (cts != null) { cts.Cancel(); } } } }
多线程解决界面卡顿问题
说明:将方法排入队列以便执行,WaitCallback,表示要执行的方法。如果将方法成功排入队列,则为 true;否则为 false。
示例:addtest方法需要比较长的时间来响应,因此在button1_Click被点击以后,程序会失去响应,使用ThreadPool.QueueUserWorkItem 后,页面会继续响应其他时间,等addtest执行结束后,响应结果。
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 多线程 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }private void button1_Click(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(new WaitCallback(addtest), "Testaa"); }private void addtest(object aa) { long result = 0; for (int i = 0; i < 1000000000; i++) { result += i; } textBox1.Text = result.ToString() + "HELLO"; } } }