C# 线程间通讯与控制

来源:百度知道 编辑:UC知道 时间:2024/09/24 13:13:14
新建一个C#控制台应用程序 在main方法中新建两个线程 分别调用两个方法 method1(),method2(),method1()用于执行一个循环,值为1-1000000000,method2()用于监听键盘输入,当输入A-Z任意键时循环暂停,按空格键循环继续,按Esc循环退出,应用程序终止,现在method1()和method2()我已经完成了,剩下的就是线程调用的问题了,已经实现了按任意键停止,但是不能继续,求高手帮忙解答,最好给段简短的代码。

使用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)