Answer the question
In order to leave comments, you need to log in
Error in a thread containing an infinite loop, how to solve?
Hello, I can not figure out what the problem is, how can I solve this situation? An exception appears when connecting through a browser to this, so to speak, server.
Description of the exception:
Unhandled exception of type 'System.InvalidOperationException' in System.dll
Additional information: This operation could not be performed after the response was sent.
at System.Net.HttpListenerResponse.set_ContentLength64(Int64 value)
at WEB_Server.ChildThread.Connections(Boolean isListening, HttpListenerContext context) at E:\Visual Studio\Projects\WEB-Server\WEB-Server\Source Code\ChildThread.cs:string 38
in WEB_Server.Program.<>c.b__9_0() in E:\Visual Studio\Projects\WEB-Server\WEB-Server\Source Code\Program.cs:line 59
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext , ContextCallback callback, Object state, Boolean preserveSyncCtx)
to System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
to System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
_t = new Thread(()=> ChildThread.Connections(_server.IsListening, _server.GetContext()));
_t.Start();
using System.Net;
using System.Text;
namespace WEB_Server
{
internal class ChildThread : Program
{
internal static void Connections(bool isListening, HttpListenerContext context)
{
while (isListening)
{
if (!Flag)
{
SwitchOff_Server();
break;
}
var request = context.Request;
if (request.HttpMethod == "POST")
{
FileIO.logHandler(request);
ShowRequestData(request);
if (!Flag) return;
}
const string responseString = @"<!DOCTYPE HTML>
<html><head></head><body>
<form method=""post"" action=""say"">
<p><b>Name: </b><br>
<input type=""text"" name=""myname"" size=""40""></p>
<p><input type=""submit"" value=""send""></p>
</form></body></html>";
var response = context.Response;
response.ContentType = "text/html; charset=UTF-8";
var buffer = Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.Length; // <=== в этом месте проявляется исключение при подключении через браузер
using (var output = response.OutputStream)
{
output.Write(buffer, 0, buffer.Length);
}
}
}
}
}
Answer the question
In order to leave comments, you need to log in
Well, according to the ContentLength description , an InvalidOperationException occurs when "The response is already being sent." Those. when the data has already been sent, the ContentLength property cannot be set.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question