我用 C# 编写了这段代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Program re = new Program();
re.actual();
}
public void actual()
{
Thread input = new Thread(input_m);
Thread timing = new Thread(timing_m);
input.Start();
timing.Start();
}
public void input_m()
{
Console.WriteLine("Choose a number from 1-10 (You have 10 seconds): ");
Console.ReadKey();
}
public void timing_m()
{
System.Threading.Thread.Sleep(10000);
input.Abort();
Console.Clear();
Console.WriteLine("Time's up!");
Console.ReadKey();
}
}
}
现在,我得到这个错误:
Error 1 The name 'input' does not exist in the current context
它说关于“input.Abort();”线。
我能以某种方式从另一个方法(而不是从它创建的地方)终止这个线程吗?
顺便说一句,我不想让它们成为静态的,所以请不要建议。
请您参考如下方法:
您需要使用类字段而不是局部变量。
class Program
{
private Thread input;
public void actual()
{
this.input = new Thread(input_m);
//...
}
}
与问题本身无关,您不应该使用多线程并强行中止从控制台读取的线程。相反,您应该结合使用 Sleep 和 Console.KeyAvailable属性(property)。
