image.png

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.Linq;
    7. using System.Text;
    8. using System.Threading;
    9. using System.Threading.Tasks;
    10. using System.Windows.Forms;
    11. namespace _112_摇奖机_多线程
    12. {
    13. public partial class Form1 : Form
    14. {
    15. public Form1()
    16. {
    17. InitializeComponent();
    18. }
    19. Thread th;
    20. bool b = true;
    21. private void button1_Click(object sender, EventArgs e)
    22. {
    23. if (button1.Text == "开始")
    24. {
    25. //Thread th = new Thread(PlayGame);
    26. th = new Thread(PlayGame);
    27. th.IsBackground = true;
    28. b = true;
    29. th.Start();
    30. button1.Text = "停止";
    31. }
    32. else
    33. {
    34. b = false;
    35. button1.Text = "开始";
    36. }
    37. }
    38. private void PlayGame()
    39. {
    40. Random r = new Random();
    41. while (b)
    42. {
    43. label1.Text = r.Next(0, 10).ToString();
    44. label2.Text = r.Next(0, 10).ToString();
    45. label3.Text = r.Next(0, 10).ToString();
    46. }
    47. }
    48. private void Form1_Load(object sender, EventArgs e)
    49. {
    50. //取消不可跨线程访问
    51. Control.CheckForIllegalCrossThreadCalls = false;
    52. }
    53. private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    54. {
    55. //当你点击关闭窗口的时候,判断线程是否为null
    56. if (th != null)
    57. {
    58. //th.Abort();//线程被Abort后就不能被Start了
    59. th = null;
    60. }
    61. }
    62. }
    63. }