在侦听用户输入时如何最好地将方法发送到另一个线程。如何最好地暂停/恢复相同的线程方法?
我试图达到的目标的精简示例:
static int fuel = 100;
static bool tankEmpty = false;
static void Main(string[] args)
{
Debug.WriteLine("test");
ThreadStart fuelThreadStart = ProcessFuel;
var fuelThread = new Thread(fuelThreadStart);
fuelThread.Start();
Console.WriteLine("Press x to add fuel");
string input = Console.ReadLine(); // < where should this go?
if (input == "x")
{
AddFuel();
}
}
static void ProcessFuel()
{
while (!tankEmpty)
{
Console.Clear();
Console.WriteLine("Current fuel level: " + fuel);
Thread.Sleep(2000);
fuel -= 10;
if (fuel < 20)
{
Console.WriteLine("Fuel level is low.");
}
}
if (tankEmpty)
{
Console.WriteLine("You have run out of fuel")
)
}
static void AddFuel()
{
if (fuel > 80)
{
fuel = 100;
}
else { }
fuel += 20;
}