问题
I have a console application which acts as a Synchronous Server Socket to receive data from a Synchronous Client Socket on the same machine.
After sending some data a few times from the Client to the Server I realize that if I were to highlight some text in the console, it would stop running code and the Client would not be able to establish a connection.
I'd like to know the reason why this happens and if there is a way to make the code still run.
回答1:
Essentially, the console is locked, to prevent it having to buffer a possibly infinite amount of data (for programs that do a lot of console IO). You can see this here:
using System;
using System.Net;
using System.Text;
using System.Threading;
static class P {
static void Main() {
using (var http = new HttpListener())
{
http.Prefixes.Add("http://localhost:20000/");
http.Start();
ThreadPool.QueueUserWorkItem(delegate {
try {
while (true) {
var ctx = http.GetContext();
Console.Write("."); // <===== this
var buffer = Encoding.UTF8.GetBytes(DateTime.Now.ToString());
ctx.Response.OutputStream.Write(buffer, 0, buffer.Length);
ctx.Response.OutputStream.Close();
}
}
catch { }
});
Console.WriteLine("Running for 5 minutes...");
Thread.Sleep(TimeSpan.FromMinutes(5));
http.Stop();
}
}
}
If you run this, it sets up a web-server that just writes the current time when you hit http://localhost:20000/. In the current code, it will interrupt the web-server if you select an area on the console, because the web-server accesses the console (not a good idea) in this line:
Console.Write("."); // <===== this
So now: remove (or comment out) that line and retry. Now, it doesn't stop the web-server when you select text on the screen, because the web-server doesn't attempt to access the console.
So to answer your question: look at any code that accesses the console in any way. This can usually be done while retaining outputs by having the main code write to some kind of queue (literally a Queue<string>
would be fine), and have a different (non-critical) thread do the writing from the queue to the console. If the output queue gets blocked: no-one cares.
来源:https://stackoverflow.com/questions/39013322/why-does-c-sharp-console-application-stop-running-when-text-is-highlighted