我正试着在控制台窗口中按Q退出。我不喜欢我现在的实现。有没有办法可以通过异步或者回调从控制台获取密钥?
发布于 2010-08-01 22:49:20
您可以从另一个线程调用Console.ReadKey(),这样它就不会阻塞您的主线程。(您可以使用.Net 4 Task或旧的Thread启动新线程。)
class Program
{
static volatile bool exit = false;
static void Main()
{
Task.Factory.StartNew(() =>
{
while (Console.ReadKey().Key != ConsoleKey.Q) ;
exit = true;
});
while (!exit)
{
// Do stuff
}
}
}发布于 2014-05-13 18:02:14
我没有发现任何现有的答案是完全令人满意的,所以我写了我自己的,使用TAP和.Net 4.5。
/// <summary>
/// Obtains the next character or function key pressed by the user
/// asynchronously. The pressed key is displayed in the console window.
/// </summary>
/// <param name="cancellationToken">
/// The cancellation token that can be used to cancel the read.
/// </param>
/// <param name="responsiveness">
/// The number of milliseconds to wait between polling the
/// <see cref="Console.KeyAvailable"/> property.
/// </param>
/// <returns>Information describing what key was pressed.</returns>
/// <exception cref="TaskCanceledException">
/// Thrown when the read is cancelled by the user input (Ctrl+C etc.)
/// or when cancellation is signalled via
/// the passed <paramred name="cancellationToken"/>.
/// </exception>
public static async Task<ConsoleKeyInfo> ReadKeyAsync(
CancellationToken cancellationToken,
int responsiveness = 100)
{
var cancelPressed = false;
var cancelWatcher = new ConsoleCancelEventHandler(
(sender, args) => { cancelPressed = true; });
Console.CancelKeyPress += cancelWatcher;
try
{
while (!cancelPressed && !cancellationToken.IsCancellationRequested)
{
if (Console.KeyAvailable)
{
return Console.ReadKey();
}
await Task.Delay(
responsiveness,
cancellationToken);
}
if (cancelPressed)
{
throw new TaskCanceledException(
"Readkey canceled by user input.");
}
throw new TaskCanceledException();
}
finally
{
Console.CancelKeyPress -= cancelWatcher;
}
}发布于 2018-06-25 17:39:48
下面是我是如何做到的:
// Comments language: pt-BR
// Aguarda key no console
private static async Task<ConsoleKey> WaitConsoleKey ( ) {
try {
// Prepara retorno
ConsoleKey key = default;
// Aguarda uma tecla ser pressionada
await Task.Run ( ( ) => key = Console.ReadKey ( true ).Key );
// Retorna a tecla
return key;
}
catch ( Exception ex ) {
throw ex;
}
}https://stackoverflow.com/questions/3382409
复制相似问题