中断到Console.ReadLine [英] Interrupt Console.ReadLine
本文介绍了中断到Console.ReadLine的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以停止到Console.ReadLine()
编程?
我有一个控制台应用程序的大部分逻辑在不同的线程运行,并在主线程我接受输入使用到Console.ReadLine()
。我想停止从控制台读取时分离出的线程停止运行。
I have a console application: the much of the logic runs on a different thread and in the main thread I accept input using Console.ReadLine()
. I'd like to stop reading from console when the separated thread stop running.
我怎样才能做到这一点?
How can I achieve this?
推荐答案
这是可能的,你必须关闭标准输入流挺举的地板垫。此程序演示的想法:
It's possible, you have to jerk the floor mat by closing the stdin stream. This program demonstrates the idea:
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);
}
}
这篇关于中断到Console.ReadLine的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文