在我们在处理事情需要的时间比较长,而且这些事情可以异步进行的时候,那么我们就可以使用多线程来同时干这些事情,提高程序执行效率并且提升CPU利用率。
单线程引发的问题
先看代码
- 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)
- {
- Test();
- }
- public void Test()
- {
-
- for (int i = 0; i < 10000; i++)
- {
- Console.WriteLine(i);
- }
- }
-
- }
- }
通过运行程序可以发现,在程序执行了button1_click事件后,for循环结束前,窗体是不响应移动和关闭事件的,为什么呢?因为当前线程在执行for循环,响应不了我们当前的操作。这就是所谓的“假死”,当for循环执行完以后,就可以执行其他的移动,关闭的事件了。
很明显,这样的程序是非常影响用户体验的,那么我们怎么能够让for循环和窗体的其他事件来异步操作,而不相互影响呢?此时,我们可以使用多线程来解决这个问题。
解决单线程带来的问题
- 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();
- }
-
- public void Test()
- {
- for (int i = 0; i < 10000; i++)
- {
- Console.WriteLine(i);
- }
- }
-
- private void button1_Click(object sender, EventArgs e)
- {
-
-
-
- Thread th = new Thread(Test);
-
-
- th.IsBackground = true;
-
-
- th.Start();
-
- }
-
-
- }
- }
再次运行这个程序,就发现我们的问题解决了,两个线程同时执行,互不影响。增加了用户体验,也使程序运行的更快。