首页 > 解决方案 > 按下键,中止线程

问题描述

我刚刚开始学习 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);
        }

标签: c#multithreading

解决方案


看起来你有一个额外的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")

这不是真的。


推荐阅读