在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
1.多线程操作 一旦打开线程就必须记得关闭 1.第一部分 这是个数字叠加小功能 private void CountTo(int countTo, CancellationToken ct) { int sum = 0; for (; countTo > 0; countTo--) { if (ct.IsCancellationRequested) { break; } sum += countTo; //Invoke方法用于获得创建lbl_Status的线程所在的上下文 this.Invoke(new Action(() => textBox2.Text = sum.ToString())); Thread.Sleep(200); } } private CancellationTokenSource _cts; private void button1_Click(object sender, EventArgs e) { _cts = new CancellationTokenSource(); ThreadPool.QueueUserWorkItem(state => CountTo(int.Parse(textBox1.Text), _cts.Token)); } 代码中Textbox1输入叠加数量的范围 ,textbox2 为显示Textbox 取消累加 private void button2_Click(object sender, EventArgs e) { if (_cts != null) _cts.Cancel(); } 2.第二部分 这是个listbox 点击添加1.2.3.4.5。。。。。直到您点击停止 Thread[] workThreads = new Thread[1]; private void button3_Click(object sender, EventArgs e) { for (int i = 0; i < workThreads.Length; i++) { if (workThreads[i] == null) { //如果线程不存在,则创建 workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); } else { //已经存在,如果没有运行,则启动 if (workThreads[i].ThreadState == ThreadState.Aborted || workThreads[i].ThreadState == ThreadState.Stopped) { workThreads[i] = new Thread(new ThreadStart(DataGet)); workThreads[i].Name = i.ToString(); workThreads[i].Start(); } else { workThreads[i].Start(); } } } } public void DataGet() { while (true) { if (listBox1.Items.Count > 0) { int text = int.Parse(listBox1.Items[listBox1.Items.Count - 1].ToString()) + 1; AddItem(text.ToString()); Thread.Sleep(1000); } } //如果此方法退出了,那么这个线程也就退出了 } private void AddItem(string text) { if (this.listBox1.InvokeRequired) { AddItemCallback d = new AddItemCallback(AddItem); this.Invoke(d, new object[] { text }); } else { this.listBox1.Items.Add(text); } }
关闭线程 private void button4_Click(object sender, EventArgs e) { this.listBox1.Items.Clear(); for (int i = 0; i < workThreads.Length; i++) { //如果线程存在,并且状态不是停止也不是终止的,则终止该线程 if (workThreads[i] != null && workThreads[i].ThreadState != ThreadState.Stopped && workThreads[i].ThreadState != ThreadState.Aborted) { workThreads[i].Abort(); } } this.listBox1.Items.Add("1"); } 3.第三部分是模仿着自己写的 //调取主板的声音 [DllImport("kernel32.dll", EntryPoint = "Beep")] public static extern int Beep(int dwFreq, int dwDuration); public void PLaySound() { for (int a = 1; a < 10; a++) { Beep(800, 1000); Beep(500, 1000); } //thread.Join(); }
private void button5_Click(object sender, EventArgs e) { thread = new Thread(new ThreadStart(PLaySound)); thread.Start(); } 关闭进程 private void button6_Click(object sender, EventArgs e) { thread.Abort(); } 进程操作有很多种,仅供自己在编程时使用
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论