Thread thread = null;
//结束子线程
private void closeThread()
{
if (thread != null)
{
if (thread.IsAlive)
{
thread.Abort();
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i <= 20; i++)
{
thread = new Thread(new ParameterizedThreadStart(work));
thread.IsBackground = true;
thread.Start(i);
}
}
Semaphore semahoro = new Semaphore(3, 3);
void work(object obj)
{
semahoro.WaitOne();
string str = "线程" + obj;
ResultOut(str);
Thread.Sleep(1000);
Application.DoEvents();
semahoro.Release();
}
//线程委托,要更新的东西
delegate void TextTmp(object obj);
private void ResultOut(object obj)
{
if (this.listBox1.InvokeRequired)
{
TextTmp tt = new TextTmp(ResultOut);
Invoke(tt, new object[] { obj });
}
else
{
this.listBox1.Items.Add(obj);
}
}
private void button1_Click(object sender, EventArgs e)
{
thread.Suspend()
}
private void button2_Click(object sender, EventArgs e)
{
thread.Resume()
}
没有暂停,需要控制请在线程内部控制,使用task替换线程
可以用过标志位来进行控制试试?
[滑稽]
semahoro.WaitOne();时是不是就停住不走了。
semahoro.Release();是不是又继续了。
我已经瞎了
使用标志位进行控制
创建thread的时候,你赋值给一个变量,上次创建的就是野线程了,给你改一下:
1 List<Thread> threads = new List<Thread>(); 2 //结束子线程 3 private void closeThread() 4 { 5 foreach (var thread in threads) 6 { 7 if (thread != null) 8 { 9 if (thread.IsAlive) 10 { 11 thread.Abort(); 12 } 13 } 14 } 15 } 16 17 private void Form1_Load(object sender, EventArgs e) 18 19 { 20 for (int i = 0; i <= 20; i++) 21 { 22 var thread = new Thread(new ParameterizedThreadStart(work)); 23 thread.IsBackground = true; 24 thread.Start(i); 25 threads.Add(thread); 26 } 27 } 28 29 30 31 Semaphore semahoro = new Semaphore(3, 3); 32 void work(object obj) 33 { 34 semahoro.WaitOne(); 35 36 string str = "线程" + obj; 37 ResultOut(str); 38 Thread.Sleep(1000); 39 Application.DoEvents(); 40 semahoro.Release(); 41 } 42 43 44 //线程委托,要更新的东西 45 delegate void TextTmp(object obj); 46 private void ResultOut(object obj) 47 { 48 if (this.listBox1.InvokeRequired) 49 { 50 TextTmp tt = new TextTmp(ResultOut); 51 Invoke(tt, new object[] { obj }); 52 } 53 else 54 { 55 this.listBox1.Items.Add(obj); 56 } 57 58 } 59 60 61 62 private void button1_Click(object sender, EventArgs e) 63 64 { 65 foreach (var thread in threads) 66 { 67 68 thread.Suspend(); 69 } 70 71 72 } 73 74 private void button2_Click(object sender, EventArgs e) 75 { 76 foreach (var thread in threads) 77 { 78 thread.Resume(); 79 } 80 }
你可以这样,使用 list 把所有 thread 对象添加进去,只对list中的其中一个下标进行操作(如 list[0]),并记录该下标,不就可以不影响其他线程操作吗