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 关注
- 153 浏览
添加回答
举报