线程界面创建过程

1. 启动2个线程,一个进行加法计算,一个进行减法计算。并且使界面不卡,随时可以拖动:

2. 在load方法中新建2个线程:

3. 两个线程分别运行加法的方法A和减法的方法B:

注意:这里需要使用Invoke,否则报错下图:

4. 效果:

代码部分

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
public partial class Form1 : Form
{

public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
ThreadStart ts1 = new ThreadStart(A);
Thread t1 = new Thread(ts1);
t1.Start();


ThreadStart ts2 = new ThreadStart(B);
Thread t2 = new Thread(ts2);
t2.Start();
}

public void A()
{
for (int i = 0; i < 20; i++)
{
Thread.Sleep(1000);
//label1.Text = i.ToString();
Invoke(new Action(() => label1.Text = i.ToString()));
}

}

public void B()
{
for (int i = 0; i < Convert.ToInt16(label2.Text); i++)
{
Thread.Sleep(1000);
Invoke(new Action(() => label2.Text = (Convert.ToInt16(label2.Text) - 1).ToString()));
}

}
}
}

相关链接

  1. c#中使用Thread

=================我是分割线=================

欢迎到公众号来唠嗑: