如何使用线程同时在控制台上读/写 [英] How to read/write on console at the same time using threads

查看:62
本文介绍了如何使用线程同时在控制台上读/写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想实现一个运行模拟的 C# 控制台应用程序.另外,我想让用户有机会在控制台上按+"或-"来加速/减速模拟的速度.

I want to implemente a C# Console Application that runs a simulation. Also, I want to give to the user the oportunity to acelerate/decelerate the speed of the simulation pressing '+' or '-' on console.

有没有办法在写入时读取控制台?我相信我可以为此使用多线程,但我不知道该怎么做(我还是 C# 新手).

Is there a way to read the console while writing on it? I believe I could use multithreading for this, but I don't how to do it (I'm still new on C#).

非常感谢!

推荐答案

您可以查看 Console.KeyAvailable 在调用 Console.ReadKey() 之前.这将让您检查控制台以查看是否有输入等待(即:用户按下 + 或 -)无阻塞.如果您只是在没有可用输入的情况下不尝试读取,您的主线程将永远不会阻塞等待用户.

You can check Console.KeyAvailable prior to calling Console.ReadKey(). This will let you check the console to see if there is input waiting (ie: the user pressed + or -) without blocking. If you just don't try to read if there is no input available, your main thread will never block waiting on the user.

使用这种机制,您实际上可以在单线程应用程序中执行此操作.

Using this mechanism, you can actually do this in a single threaded application.

这篇关于如何使用线程同时在控制台上读/写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆