c# - 在侦听用户输入时在不同的线程上运行方法
问题描述
在侦听用户输入的同时如何最好地将方法发送到另一个线程。如何最好地暂停/恢复相同的线程方法?
我试图实现的那种事情的一个非常精简的例子:
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;
}
解决方案
推荐阅读
- java - 同时创建列表和插入值与分两步有什么区别?
- java - 如何为特定路径重定向到 404 上的默认资源文件
- woocommerce - 使用 ionic 4 将数据发布到 woocommerce api v3 时出现 401 未经授权的错误
- python - 如何在 django rest API 框架中登录自定义用户模型
- javascript - 提取多个段的问题
- python - pyinstaller:使用 --key 命令时出现问题
- google-docs - 谷歌文档 - 是否有任何功能支持谷歌文档(没有谷歌表格)从范围中选择值?
- android - 我在运行模拟器时收到了日志中的消息 == 模拟器:尝试在 eip:1000f0 处执行 vcpu
- python - 为什么我在 Okta OAuth2.0 /api/v1/authorize 端点上收到“E0000022”?
- feature-extraction - MFCC 特征提取,Librosa