C#多线程编程实例 线程与窗体交互

c语言隐藏线程图解(C井多线程编程实例)(1)

代码:

  1. public partial class Form1 : Form
  2. {
  3. //声明线程数组
  4. Thread[] workThreads = new Thread[10];
  5. public Form1()
  6. {
  7. InitializeComponent();
  8. }
  9. //此委托允许异步的调用为Listbox添加Item
  10. delegate void AddItemCallback(string text);
  11. //这种方法演示如何在线程安全的模式下调用Windows窗体上的控件。
  12. private void AddItem(string text)
  13. {
  14. if (this.listBox1.InvokeRequired)
  15. {
  16. AddItemCallback d = new AddItemCallback(AddItem);
  17. this.Invoke(d, new object[] { text });
  18. }
  19. else
  20. {
  21. this.listBox1.Items.Add(text);
  22. }
  23. }
  24. //数据采集方法
  25. public void DataGet()
  26. {
  27. while (true)
  28. {
  29. AddItem("ok");
  30. Thread.Sleep(1000);
  31. }
  32. //如果此方法退出了,那么这个线程也就退出了
  33. }
  34. /// <summary>
  35. /// 启动线程
  36. /// </summary>
  37. /// <param name="sender"></param>
  38. /// <param name="e"></param>
  39. private void button1_Click(object sender, EventArgs e)
  40. {
  41. //循环创建并启动线程执行
  42. for (int i = 0; i < workThreads.Length; i )
  43. {
  44. if (workThreads[i] == null)
  45. {
  46. //如果线程不存在,则创建
  47. workThreads[i] = new Thread(new ThreadStart(DataGet));
  48. workThreads[i].Name = i.ToString();
  49. workThreads[i].Start();
  50. }
  51. else
  52. {
  53. //已经存在,如果没有运行,则启动
  54. if (workThreads[i].ThreadState == ThreadState.Aborted || workThreads[i].ThreadState == ThreadState.Stopped)
  55. {
  56. workThreads[i] = new Thread(new ThreadStart(DataGet));
  57. workThreads[i].Name = i.ToString();
  58. workThreads[i].Start();
  59. }else{
  60. workThreads[i].Start();
  61. }
  62. }
  63. }
  64. }
  65. /// <summary>
  66. /// 停止线程
  67. /// </summary>
  68. /// <param name="sender"></param>
  69. /// <param name="e"></param>
  70. private void button2_Click(object sender, EventArgs e)
  71. {
  72. //循环停止线程执行
  73. for (int i = 0; i < workThreads.Length; i )
  74. {
  75. //如果线程存在,并且状态不是停止也不是终止的,则终止该线程
  76. if (workThreads[i] != null && workThreads[i].ThreadState != ThreadState.Stopped && workThreads[i].ThreadState != ThreadState.Aborted)
  77. {
  78. workThreads[i].Abort();
  79. }
  80. }
  81. }
  82. }

源码下载:http://download.csdn.net/detail/testcs_dn/7618881

,