c# - 按下键,中止线程
问题描述
我刚刚开始学习 C#,我正在尝试找出线程。
所以,我创建了两个线程,我想通过按 x 来停止其中一个线程。
到目前为止,当我按 x 时,它只显示在控制台上,但不会中止线程。
我显然做错了什么,所以有人可以指出我做错了什么吗?谢谢你。
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Creating Threads
Thread t1 = new Thread(Method1)
{
Name = "Thread1"
};
Thread t4 = new Thread(Method4)
{
Name = "Thread4"
};
t1.Start();
t4.Start();
Console.WriteLine("Method4 has started. Press x to stop it. You have 5 SECONDS!!!");
var input = Console.ReadKey();
string input2 = input.Key.ToString();
Console.ReadKey();
if (input2 == "x")
{
t4.Abort();
Console.WriteLine("SUCCESS! You have stoped Thread4! Congrats.");
};
Console.Read();
}
static void Method1()
{
Console.WriteLine("Method1 Started using " + Thread.CurrentThread.Name);
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method1: " + i);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Method1 Ended using " + Thread.CurrentThread.Name);
}
static void Method4()
{
Console.WriteLine("Method4 Started using " + Thread.CurrentThread.Name);
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("Method4: " + i);
System.Threading.Thread.Sleep(1000);
}
Console.WriteLine("Method4 Ended using " + Thread.CurrentThread.Name);
}
解决方案
看起来你有一个额外的Console.ReadKey();
before if (input2 == "x")
,额外的读取会导致程序在进入你的if
语句等待按下第二个键之前停止并等待。
还input.Key
返回一个enum,当您在其上执行 to 字符串时,枚举将使用大写 X,因为这是它的设置。使用input.KeyChar.ToString()
将其转换为字符串或使用
var input = Console.ReadKey();
if (input.Key == ConsoleKey.X)
与枚举而不是字符串进行比较。
我还建议您阅读文章“如何调试小程序”,调试是您需要学习的一项技能,以便能够编写更复杂的程序。使用您会看到的调试器单步执行代码input2
等于,X
因此您的 if 语句是
if ("X" == "x")
这不是真的。
推荐阅读
- c# - 在文本框中输入的值内使用 LIKE 搜索
- elasticsearch - Kibana 索引模式刷新选项不再存在
- python-imaging-library - 将图像转换为 .ico 文件的问题
- angularjs - Angular 创建具有特定名称的新组件
- spring-boot - Spring Boot JPA计数查询按多个字段
- django - 我可以用 mock.patch('django.utils.timezone.now', mock.Mock(return_value=mocked)) 测试 celery 吗?
- regex - 如何替换字符串的多个子出现
- c++ - 如何在没有现有数据库的情况下缩短现有 C++ 代码
- c# - 在 C# 解决方案中查找并指示未引用的公共属性
- javascript - 当我尝试在 firebase 上部署反应应用程序时,npm run build 返回错误