1 回答

TA貢獻1799條經驗 獲得超6個贊
使用Thread的Suspend方法可以暫停一個線程,Resume繼續,給你寫個例子吧
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static Thread th1;
static Thread th2;
static int value = 0;
static void Main(string[] args)
{
th1 = new Thread(new ThreadStart(Method1));
th2 = new Thread(new ThreadStart(Method2));
th1.Start();
th2.Start();
}
static void Method1()
{
for (int i = 0; i < 1000000000; i++)
{
value++;
}
Console.WriteLine("完成");
}
static void Method2()
{
while (true)
{
ConsoleKeyInfo read = Console.ReadKey();
if (char.IsLetter(read.KeyChar))
{
if (th1.ThreadState == ThreadState.Stopped)
{
Console.WriteLine("th1已停止,按Esc鍵退出");
continue;
}
th1.Suspend();
Console.WriteLine("th1已掛起,value為{0}", value);
}
else if (read.Key == ConsoleKey.Spacebar)
{
if (th1.ThreadState == ThreadState.Stopped)
{
Console.WriteLine("th1已停止,按Esc鍵退出");
continue;
}
else if (th1.ThreadState == ThreadState.Running)
{
Console.WriteLine("th1正在運行");
continue;
}
th1.Resume();
Console.WriteLine("th1繼續運行");
}
else if (read.Key == ConsoleKey.Escape)
{
th1.Abort();
th2.Abort();
return;
}
}
}
}
}
- 1 回答
- 0 關注
- 178 瀏覽
添加回答
舉報