如何中断Console.ReadLine

本文关键字:Console ReadLine 中断 何中断 | 更新日期: 2023-09-27 18:26:04

是否可以通过编程方式停止Console.ReadLine()

我有一个控制台应用程序:大部分逻辑运行在不同的线程上,在主线程中,我使用Console.ReadLine()接受输入。当分离的线程停止运行时,我想停止从控制台读取。

我怎样才能做到这一点?

如何中断Console.ReadLine

更新:此技术在Windows 10上不再可靠。请不要用它
Win10中相当繁重的实现更改,使控制台更像一个终端。毫无疑问,将协助开发新的Linux子系统。一个(意外的?)副作用是CloseHandle()死锁,直到读取完成,从而扼杀了这种方法。我会保留原来的帖子,只是因为它可能会帮助某人找到替代方案。

更新2:看看wischi的答案,找到一个不错的替代方案。


这是可能的,你必须通过关闭stdin流来猛拉地板垫。这个程序展示了这个想法:

using System;
using System.Threading;
using System.Runtime.InteropServices;
namespace ConsoleApplication2 {
    class Program {
        static void Main(string[] args) {
            ThreadPool.QueueUserWorkItem((o) => {
                Thread.Sleep(1000);
                IntPtr stdin = GetStdHandle(StdHandle.Stdin);
                CloseHandle(stdin);
            });
            Console.ReadLine();
        }
        // P/Invoke:
        private enum StdHandle { Stdin = -10, Stdout = -11, Stderr = -12 };
        [DllImport("kernel32.dll")]
        private static extern IntPtr GetStdHandle(StdHandle std);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hdl);
    }
}

将[enter]发送到当前运行的控制台应用程序:

    class Program
    {
        [DllImport("User32.Dll", EntryPoint = "PostMessageA")]
        private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
        const int VK_RETURN = 0x0D;
        const int WM_KEYDOWN = 0x100;
        static void Main(string[] args)
        {
            Console.Write("Switch focus to another window now.'n");
            ThreadPool.QueueUserWorkItem((o) =>
            {
                Thread.Sleep(4000);
                var hWnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
                PostMessage(hWnd, WM_KEYDOWN, VK_RETURN, 0);
            });
            Console.ReadLine();
            Console.Write("ReadLine() successfully aborted by background thread.'n");
            Console.Write("[any key to exit]");
            Console.ReadKey();
        }
    }

这段代码将[enter]发送到当前控制台进程,中止在windows内核深处的非托管代码中阻塞的任何ReadLine()调用,这允许C#线程自然退出。

我使用了这段代码,而不是关闭控制台的答案,因为关闭控制台意味着ReadLine()和ReadKey()从此代码中被永久禁用(如果使用它,它将引发异常)。

这个答案优于所有涉及SendKeys和Windows输入模拟器的解决方案,因为即使当前应用程序没有焦点,它也能工作。

免责声明:这只是一个副本&粘贴答案。

感谢Gérald Barré提供了如此出色的解决方案:
https://www.meziantou.net/cancelling-console-read.htm

CancelIoEX的文档:
https://learn.microsoft.com/en-us/windows/win32/fileio/cancelioex-func

我在Windows 10上测试过。它工作得很好,而且比其他解决方案(如重新实现Console.ReadLine、通过PostMessage发送返回或关闭句柄,如接受的答案)

如果网站宕机,我在这里引用代码片段:

class Program
{
    const int STD_INPUT_HANDLE = -10;
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr GetStdHandle(int nStdHandle);
    [DllImport("kernel32.dll", SetLastError = true)]
    static extern bool CancelIoEx(IntPtr handle, IntPtr lpOverlapped);
    static void Main(string[] args)
    {
        // Start the timeout
        var read = false;
        Task.Delay(10000).ContinueWith(_ =>
        {
            if (!read)
            {
                // Timeout => cancel the console read
                var handle = GetStdHandle(STD_INPUT_HANDLE);
                CancelIoEx(handle, IntPtr.Zero);
            }
        });
        try
        {
            // Start reading from the console
            Console.WriteLine("Do you want to continue [Y/n] (10 seconds remaining):");
            var key = Console.ReadKey();
            read = true;
            Console.WriteLine("Key read");
        }
        // Handle the exception when the operation is canceled
        catch (InvalidOperationException)
        {
            Console.WriteLine("Operation canceled");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation canceled");
        }
    }
}

我需要一个可以使用Mono的解决方案,所以没有API调用。我发布这篇文章只是为了让其他处于同样情况的人,或者想要一种纯粹的C#方式来做这件事。CreateKeyInfoFromInt()函数是一个棘手的部分(有些键的长度超过一个字节)。在下面的代码中,如果从另一个线程调用ReadKeyReset(),则ReadKey()会引发异常。下面的代码并不完全完整,但它确实演示了使用现有控制台C#函数创建可中断GetKey()函数的概念。

static ManualResetEvent resetEvent = new ManualResetEvent(true);
/// <summary>
/// Resets the ReadKey function from another thread.
/// </summary>
public static void ReadKeyReset()
{
    resetEvent.Set();
}
/// <summary>
/// Reads a key from stdin
/// </summary>
/// <returns>The ConsoleKeyInfo for the pressed key.</returns>
/// <param name='intercept'>Intercept the key</param>
public static ConsoleKeyInfo ReadKey(bool intercept = false)
{
    resetEvent.Reset();
    while (!Console.KeyAvailable)
    {
        if (resetEvent.WaitOne(50))
            throw new GetKeyInteruptedException();
    }
    int x = CursorX, y = CursorY;
    ConsoleKeyInfo result = CreateKeyInfoFromInt(Console.In.Read(), false);
    if (intercept)
    {
        // Not really an intercept, but it works with mono at least
        if (result.Key != ConsoleKey.Backspace)
        {
            Write(x, y, " ");
            SetCursorPosition(x, y);
        }
        else
        {
            if ((x == 0) && (y > 0))
            {
                y--;
                x = WindowWidth - 1;
            }
            SetCursorPosition(x, y);
        }
    }
    return result;
}

我也在寻找一种在某些情况下停止从控制台读取的方法。我想出的解决方案是用这两种方法制作一个读行的非阻塞版本。

static IEnumerator<Task<string>> AsyncConsoleInput()
{
    var e = loop(); e.MoveNext(); return e;
    IEnumerator<Task<string>> loop()
    {
        while (true) yield return Task.Run(() => Console.ReadLine());
    }
}
static Task<string> ReadLine(this IEnumerator<Task<string>> console)
{
    if (console.Current.IsCompleted) console.MoveNext();
    return console.Current;
}

这允许我们在单独的线程上拥有ReadLine,我们可以等待它,也可以有条件地在其他地方使用它。

var console = AsyncConsoleInput();
var task = Task.Run(() =>
{
     // your task on separate thread
});
if (Task.WaitAny(console.ReadLine(), task) == 0) // if ReadLine finished first
{
    task.Wait();
    var x = console.Current.Result; // last user input (await instead of Result in async method)
}
else // task finished first 
{
    var x = console.ReadLine(); // this wont issue another read line because user did not input anything yet. 
}

当前接受的答案不再有效,所以我决定创建一个新的答案。做到这一点的唯一安全方法是创建自己的ReadLine方法。我可以想到许多需要这种功能的场景,这里的代码实现了其中之一:

public static string CancellableReadLine(CancellationToken cancellationToken)
{
    StringBuilder stringBuilder = new StringBuilder();
    Task.Run(() =>
    {
        try
        {
            ConsoleKeyInfo keyInfo;
            var startingLeft = Con.CursorLeft;
            var startingTop = Con.CursorTop;
            var currentIndex = 0;
            do
            {
                var previousLeft = Con.CursorLeft;
                var previousTop = Con.CursorTop;
                while (!Con.KeyAvailable)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    Thread.Sleep(50);
                }
                keyInfo = Con.ReadKey();
                switch (keyInfo.Key)
                {
                    case ConsoleKey.A:
                    case ConsoleKey.B:
                    case ConsoleKey.C:
                    case ConsoleKey.D:
                    case ConsoleKey.E:
                    case ConsoleKey.F:
                    case ConsoleKey.G:
                    case ConsoleKey.H:
                    case ConsoleKey.I:
                    case ConsoleKey.J:
                    case ConsoleKey.K:
                    case ConsoleKey.L:
                    case ConsoleKey.M:
                    case ConsoleKey.N:
                    case ConsoleKey.O:
                    case ConsoleKey.P:
                    case ConsoleKey.Q:
                    case ConsoleKey.R:
                    case ConsoleKey.S:
                    case ConsoleKey.T:
                    case ConsoleKey.U:
                    case ConsoleKey.V:
                    case ConsoleKey.W:
                    case ConsoleKey.X:
                    case ConsoleKey.Y:
                    case ConsoleKey.Z:
                    case ConsoleKey.Spacebar:
                    case ConsoleKey.Decimal:
                    case ConsoleKey.Add:
                    case ConsoleKey.Subtract:
                    case ConsoleKey.Multiply:
                    case ConsoleKey.Divide:
                    case ConsoleKey.D0:
                    case ConsoleKey.D1:
                    case ConsoleKey.D2:
                    case ConsoleKey.D3:
                    case ConsoleKey.D4:
                    case ConsoleKey.D5:
                    case ConsoleKey.D6:
                    case ConsoleKey.D7:
                    case ConsoleKey.D8:
                    case ConsoleKey.D9:
                    case ConsoleKey.NumPad0:
                    case ConsoleKey.NumPad1:
                    case ConsoleKey.NumPad2:
                    case ConsoleKey.NumPad3:
                    case ConsoleKey.NumPad4:
                    case ConsoleKey.NumPad5:
                    case ConsoleKey.NumPad6:
                    case ConsoleKey.NumPad7:
                    case ConsoleKey.NumPad8:
                    case ConsoleKey.NumPad9:
                    case ConsoleKey.Oem1:
                    case ConsoleKey.Oem102:
                    case ConsoleKey.Oem2:
                    case ConsoleKey.Oem3:
                    case ConsoleKey.Oem4:
                    case ConsoleKey.Oem5:
                    case ConsoleKey.Oem6:
                    case ConsoleKey.Oem7:
                    case ConsoleKey.Oem8:
                    case ConsoleKey.OemComma:
                    case ConsoleKey.OemMinus:
                    case ConsoleKey.OemPeriod:
                    case ConsoleKey.OemPlus:
                        stringBuilder.Insert(currentIndex, keyInfo.KeyChar);
                        currentIndex++;
                        if (currentIndex < stringBuilder.Length)
                        {
                            var left = Con.CursorLeft;
                            var top = Con.CursorTop;
                            Con.Write(stringBuilder.ToString().Substring(currentIndex));
                            Con.SetCursorPosition(left, top);
                        }
                        break;
                    case ConsoleKey.Backspace:
                        if (currentIndex > 0)
                        {
                            currentIndex--;
                            stringBuilder.Remove(currentIndex, 1);
                            var left = Con.CursorLeft;
                            var top = Con.CursorTop;
                            if (left == previousLeft)
                            {
                                left = Con.BufferWidth - 1;
                                top--;
                                Con.SetCursorPosition(left, top);
                            }
                            Con.Write(stringBuilder.ToString().Substring(currentIndex) + " ");
                            Con.SetCursorPosition(left, top);
                        }
                        else
                        {
                            Con.SetCursorPosition(startingLeft, startingTop);
                        }
                        break;
                    case ConsoleKey.Delete:
                        if (stringBuilder.Length > currentIndex)
                        {
                            stringBuilder.Remove(currentIndex, 1);
                            Con.SetCursorPosition(previousLeft, previousTop);
                            Con.Write(stringBuilder.ToString().Substring(currentIndex) + " ");
                            Con.SetCursorPosition(previousLeft, previousTop);
                        }
                        else
                            Con.SetCursorPosition(previousLeft, previousTop);
                        break;
                    case ConsoleKey.LeftArrow:
                        if (currentIndex > 0)
                        {
                            currentIndex--;
                            var left = Con.CursorLeft - 2;
                            var top = Con.CursorTop;
                            if (left < 0)
                            {
                                left = Con.BufferWidth + left;
                                top--;
                            }
                            Con.SetCursorPosition(left, top);
                            if (currentIndex < stringBuilder.Length - 1)
                            {
                                Con.Write(stringBuilder[currentIndex].ToString() + stringBuilder[currentIndex + 1]);
                                Con.SetCursorPosition(left, top);
                            }
                        }
                        else
                        {
                            Con.SetCursorPosition(startingLeft, startingTop);
                            if (stringBuilder.Length > 0)
                                Con.Write(stringBuilder[0]);
                            Con.SetCursorPosition(startingLeft, startingTop);
                        }
                        break;
                    case ConsoleKey.RightArrow:
                        if (currentIndex < stringBuilder.Length)
                        {
                            Con.SetCursorPosition(previousLeft, previousTop);
                            Con.Write(stringBuilder[currentIndex]);
                            currentIndex++;
                        }
                        else
                        {
                            Con.SetCursorPosition(previousLeft, previousTop);
                        }
                        break;
                    case ConsoleKey.Home:
                        if (stringBuilder.Length > 0 && currentIndex != stringBuilder.Length)
                        {
                            Con.SetCursorPosition(previousLeft, previousTop);
                            Con.Write(stringBuilder[currentIndex]);
                        }
                        Con.SetCursorPosition(startingLeft, startingTop);
                        currentIndex = 0;
                        break;
                    case ConsoleKey.End:
                        if (currentIndex < stringBuilder.Length)
                        {
                            Con.SetCursorPosition(previousLeft, previousTop);
                            Con.Write(stringBuilder[currentIndex]);
                            var left = previousLeft + stringBuilder.Length - currentIndex;
                            var top = previousTop;
                            while (left > Con.BufferWidth)
                            {
                                left -= Con.BufferWidth;
                                top++;
                            }
                            currentIndex = stringBuilder.Length;
                            Con.SetCursorPosition(left, top);
                        }
                        else
                            Con.SetCursorPosition(previousLeft, previousTop);
                        break;
                    default:
                        Con.SetCursorPosition(previousLeft, previousTop);
                        break;
                }
            } while (keyInfo.Key != ConsoleKey.Enter);
            Con.WriteLine();
        }
        catch
        {
            //MARK: Change this based on your need. See description below.
            stringBuilder.Clear();
        }
    }).Wait();
    return stringBuilder.ToString();
}

把这个函数放在代码中的某个地方,这给了你一个可以通过CancellationToken取消的函数。为了更好的代码,我使用了

using Con = System.Console;

此函数在取消时返回一个空字符串(这对我的情况很好),如果您愿意,可以在上面标记的catch表达式中抛出异常。

同样,在相同的catch表达式中,您可以删除stringBuilder.Clear();行,这将导致代码返回用户迄今为止输入的内容。将其与成功或取消的标志相结合,您可以保留到目前为止输入的已用标志,并在进一步的请求中使用它。

您可以更改的另一件事是,如果您想获得超时功能,您可以在循环中设置除取消令牌之外的超时。

我尽量做到干净,但这个代码可以更干净。该方法可以成为async本身以及传入的超时和取消令牌。

我知道这个问题很老,而且早于.NET Core,但我认为添加一个更现代的方法会很有用。

我已经在.NET6中测试了这种方法。我创建了一个简单的异步ReadLine方法,它使用一个可以用来中断它的取消令牌

关键是将Console.ReadLine()封装在任务中。显然,Console.ReadLine()调用不能被中断,因此Task.WhenAny与Task.Delay结合使用以使取消令牌工作。

为了不丢失任何输入,读取任务被保留在方法之外,因此如果操作被取消,则可以在下一次调用中等待它。

Task<string?>? readTask = null;
async Task<string?> ReadLineAsync(CancellationToken cancellationToken = default)
{
    readTask ??= Task.Run(() => Console.ReadLine());
    await Task.WhenAny(readTask, Task.Delay(-1, cancellationToken));
    cancellationToken.ThrowIfCancellationRequested();
    string? result = await readTask;
    readTask = null;
    return result;
}

因此,这里有一个在Windows 10上运行的解决方案,不使用任何花哨的线程或dllimport魔术。它对我来说很好,我希望它能有所帮助。

我基本上是在标准输入上创建一个流式阅读器。读起来有点"异步;如果我想取消读行,只需处理流读取器。

这是我的代码:

    private System.IO.StreamReader stdinsr = new System.IO.StreamReader(Console.OpenStandardInput());
    [DebuggerHidden]
    private string ReadLine() {
        return stdinsr.ReadLineAsync().Result;
    }
    protected override void OnExit(ExitEventArgs e) {
        base.OnExit(e);
        commandLooper.Abort();
        stdinsr.Dispose();
    }

注意:是的,我读异步,但我在等待任务结果,所以它基本上仍在等待用户输入。

这是Contango答案的修改版本。如果从cmd启动,此代码将使用GetForegroundWindow()来获取控制台的MainWindowhandle,而不是使用当前进程的MainWindowhandle。

using System;
using System.Runtime.InteropServices;
public class Temp
{
    //Just need this
    //==============================
    static IntPtr ConsoleWindowHnd = GetForegroundWindow();
    [DllImport("user32.dll")]
    static extern IntPtr GetForegroundWindow();
    [DllImport("User32.Dll")]
    private static extern bool PostMessage(IntPtr hWnd, uint msg, int wParam, int lParam);
    const int VK_RETURN = 0x0D;
    const int WM_KEYDOWN = 0x100;
    //==============================
    public static void Main(string[] args)
    {
        System.Threading.Tasks.Task.Run(() =>
        {
            System.Threading.Thread.Sleep(2000);
            //And use like this
            //===================================================
            PostMessage(ConsoleWindowHnd, WM_KEYDOWN, VK_RETURN, 0);
            //===================================================
        });
        Console.WriteLine("Waiting");
        Console.ReadLine();
        Console.WriteLine("Waiting Done");
        Console.Write("Press any key to continue . . .");
        Console.ReadKey();
    }
}

可选

检查前台窗口是否为cmd。如果不是,那么当前进程应该启动控制台窗口,所以继续使用它。这并不重要,因为前台窗口无论如何都应该是当前进程窗口,但这可以通过反复检查来帮助您感觉良好。

    int id;
    GetWindowThreadProcessId(ConsoleWindowHnd, out id);
    if (System.Diagnostics.Process.GetProcessById(id).ProcessName != "cmd")
    {
        ConsoleWindowHnd = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
    }

我刚刚在GitHub上偶然发现了这个小库:https://github.com/tonerdo/readline

ReadLine是一个类似GNU ReadLine的纯C#库。它可以发球作为内置控制台的替代品。ReadLine()并带来此外,您还可以从unix shell中获得一些终端优点,比如命令历史导航和选项卡自动完成。

它是跨平台的,可以在任何支持.NET的地方运行,目标是netstandard1.3意味着它可以与.NET Core以及完整的.NET框架。

虽然这个库不支持在编写时中断输入,但更新它应该很简单。或者,它可以是一个有趣的例子,说明如何编写自定义解决方案来克服Console.ReadLine的限制。

当您的应用程序等待控制台时,这将在一个单独的线程中处理Ctrl+C。Readline():

Console.CancelKeyPress += (_, e) =>
{
    e.Cancel = true;
    Environment.Exit(0);
};