C# winform动态创建多线程

C# winform动态创建多线程,第1张

1 private void Form1_Load(object sender, EventArgs e)

2 {

3 Thread newthread = new Thread(new ThreadStart(BackgroundProcess))

4 newthread.Start()

5

6 }

7

8 /// <summary>

9 /// 定义一个代理

10 /// </扰燃链summary>

11 private delegate void CrossThreadOperationControl()

12

13 private void BackgroundProcess()

14 {

15 // 将代理实例化为一个匿名代理

16 CrossThreadOperationControl CrossDelete = delegate()

17 {

18 int i = 1

19 while (i <5)

20 {

21 // 向列表框增加一个项目

22 listBox1.Items.Add("Item " + i.ToString())

23 i++

24 }

25 label1.Text = "我在新线程里访问这个段告lable!"

26 listBox1.Items.Add(label1.Text)

27 }

28 listBox1.Invoke(CrossDelete)

29 }

收集一下,在C# winform编程中多线程 *** 作控件时,可以有下面种方法:

1. 又看到一种方法(2014.1.6):

1. 刚缓孙看到一种方法(2014.1.5):

1 private void btnTest_Click(object sender, EventArgs e)

2 {

3 if (this.txtIP.Text.Trim() != "" &&this.txtPort.Text.Trim() != "")

4 {

5 string proxy = this.txtIP.Text.Trim() + ":" + this.txtPort.Text.Trim()

6 string result = string.Empty

7 this.btnTest.Enabled = false

8 new Thread(delegate

9 {

10 Stopwatch stopwatch = new Stopwatch()

11 stopwatch.Start()

12 HttpClient httpClient = new HttpClient()

13 httpClient.Proxy = new WebProxy(proxy)

14 httpClient.TimeOut = 2000

15 object result

16 try

17 {

18 string a = httpClient.Get("http://www.baidu.com", "", "", "", "", "get")

19 if (a != "")

20 {

21 result = "响应成功!"

22 }

23 else

24 {

25 result = "响应失败!"

26 }

27 }

28 catch

29 {

30 }

31 stopwatch.Stop()

32 result = result

33 result = string.Concat(new object[]

34 {

35 result,

36 ",响应花费:",

37 stopwatch.ElapsedMilliseconds,

38 "ms"

39 })

40 this.BeginInvoke(delegate

41 {

42 this.lbResult.Text = result

43 this.btnTest.Enabled = true

44 })

45 })

46 {

47 IsBackground = true

48 }.Start()

49 }

50 else

51 {

52 this.lbResult.Text = "请输入完整再提交!"

53 }

54 }

1. 直接使用表达式和Action()

1 private void btnInitEnv_Click(object sender, EventArgs e)

2 {

3 //初始化环境时回显出来的文字不让看

4 try

5 {

6 this.textBoxOutPut.Clear()

7 this.btnInitEnv.Enabled = false

8 this.labelStateInfo.Text = ""

9 this.labelStateInfo.ForeColor = Color.Red

10

11 if (!WriteToSerialPort("diags"))

12 {

13 this.btnInitEnv.Enabled = true

14 return

15 }

16

17 Thread thread = new Thread(new ThreadStart(() =>

18 {

19 int i = 0

20 bool flagFind = false

21 StringBuilder sb = new StringBuilder()

22

23 while (true)

24 {

25 Thread.Sleep(300)

26 this.Invoke(new Action(() =>

27 {

28 sb.Append(this.textBoxOutPut.Text)

29 this.textBoxOutPut.Clear()

30 if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))

31 {

32 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,

33 DateTime.Now.ToString(PubilcConstVar.TimeFormat),

34 "Entering recovery mode, starting command prompt, Stop.\r\n"))

35 this.labelStateInfo.ForeColor = Color.Red

36 this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化"

37 flagFind = true

38 this.btnInitEnv.Enabled = true

39 }

40 else if (sb.ToString().Contains(":-)"))

41 {

42 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,

43 DateTime.Now.ToString(PubilcConstVar.TimeFormat),

44 "进入 *** 作模式成功\r\n"))

45 this.labelStateInfo.ForeColor = Color.Blue

46 this.labelStateInfo.Text = "初始化成功"

47 flagFind = true

48

49 //将业务按钮使能

50 EnableBussinessButtons()

51 }

52 }))

53

54 if (flagFind || ++i >20) //找开标志或10秒超时中断

55 {

56 break

57 }

58 }

59

60 if (!flagFind)

61 {

62 this.Invoke(new Action(() =>

63 {

64 this.textBoxOutPut.Clear()

65 this.labelStateInfo.ForeColor = Color.Red

66 this.labelStateInfo.Text = "初始化失败,超时"

67 this.btnInitEnv.Enabled = true

68

69 DisableBussinessButtons()

70 }))

71 }

72 }))

73

74 thread.IsBackground = true

75 thread.Start()

76 }

77 catch (Exception ex)

78 {

79 this.log.Write(ex.ToString())

80 }

81 }

2. 使用线程函数加action()

1 private void btnInitEnv_Click(object sender, EventArgs e)

2 {

3 //初始化环境时回显出来的文字不让看

4 try

5 {

6 this.textBoxOutPut.Clear()

7 this.btnInitEnv.Enabled = false

8 this.labelStateInfo.Text = ""

9 this.labelStateInfo.ForeColor = Color.Red

10

11 if (!WriteToSerialPort("diags"))

12 {

13 this.btnInitEnv.Enabled = true

14 return

15 }

16

17 Thread thread = new Thread(new ThreadStart(MonitorOutPutThread))

18

19 thread.IsBackground = true

20 thread.Start()

21 }

22 catch (Exception ex)

23 {

24 this.log.Write(ex.ToString())

25 }

26 }

线程函数:

1 private void MonitorOutPutThread()

2 {

3 int i = 0

4 bool flagFind = false

5 StringBuilder sb = new StringBuilder()

6

7 while (true)

8 {

9 Thread.Sleep(300)

10 this.Invoke(new Action(() =>

11 {

12 sb.Append(this.textBoxOutPut.Text)

13 this.textBoxOutPut.Clear()

14 if (sb.ToString().Contains("Entering recovery mode, starting command prompt"))

15 {

16 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,

17 DateTime.Now.ToString(PubilcConstVar.TimeFormat),

18 "Entering recovery mode, starting command prompt, Stop.\r\n"))

19 this.labelStateInfo.ForeColor = Color.Red

20 this.labelStateInfo.Text = "初始化失败,请手动输入命令初始化"

21 flagFind = true

22 this.btnInitEnv.Enabled = true

23 }

24 else if (sb.ToString().Contains(":-)"))

25 {

26 this.textBoxOutPut.AppendText(string.Format(PubilcConstVar.TerimalStrFormat,

27 DateTime.Now.ToString(PubilcConstVar.TimeFormat),

28 "进入 *** 作模式成功\r\n"))

29 this.labelStateInfo.ForeColor = Color.Blue

30 this.labelStateInfo.Text = "初始化成功"

31 flagFind = true

32

33 //将业务按钮使能

34 EnableBussinessButtons()

35 }

36 }))

37

38 if (flagFind || ++i >20) //找开标志或10秒超时中断

39 {

40 break

41 }

42 }

43

44 if (!flagFind)

45 {

46 this.Invoke(new Action(() =>

47 {

48 this.textBoxOutPut.Clear()

49 this.labelStateInfo.ForeColor = Color.Red

50 this.labelStateInfo.Text = "初始化失败,超时"

51 this.btnInitEnv.Enabled = true

52

53 DisableBussinessButtons()

54 }))

55 }

56 }

一般在一些网扒亮络软件方面需要多线程,单单是管理软件什么的不需要。

在网络软件的话,需要有芦扰一个一直读取数据的方法,需要读取远程发来的信息。

方法就是一个死循环。这里如果不用多线程的话,程序一打开就什么也干不陪此旦了。开了多线程,那个线程就只会干读取这件事,主线程就可以发消息干其他事,两个线程不会相互影响。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/yw/12371618.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存