首页 > 解决方案 > 在侦听用户输入时在不同的线程上运行方法

问题描述

在侦听用户输入的同时如何最好地将方法发送到另一个线程。如何最好地暂停/恢复相同的线程方法?

我试图实现的那种事情的一个非常精简的例子:

    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;
    }

标签: c#multithreadingconsole-application

解决方案


推荐阅读