Skip to content

Commit

Permalink
Additional changes to threading
Browse files Browse the repository at this point in the history
  • Loading branch information
Kaliumhexacyanoferrat committed Mar 17, 2020
1 parent c8f5426 commit 1794d57
Show file tree
Hide file tree
Showing 7 changed files with 85 additions and 91 deletions.
13 changes: 7 additions & 6 deletions Core/GenHTTP.Core/Infrastructure/Endpoints/EndPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ protected EndPoint(IServer server, IPEndPoint endPoint, NetworkConfiguration con
throw new BindingException($"Failed to bind to {endPoint}.", e);
}


Task = Task.Run(() => Listen());
Task = Task.Factory.StartNew(() => Listen(), CancellationToken.None, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning, TaskScheduler.Default);
}

#endregion
Expand All @@ -77,7 +76,7 @@ private async Task Listen()
{
do
{
Handle(await Socket.AcceptAsync());
Handle(await Socket.AcceptAsync().ConfigureAwait(false));
}
while (!shuttingDown);
}
Expand All @@ -92,15 +91,17 @@ private async Task Listen()

private void Handle(Socket client)
{
Task.Factory.StartNew(state => Accept((Socket)state), client, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
Task.Factory.StartNew(state => Accept((Socket)state), client, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default)
.ConfigureAwait(false);
}

protected abstract Task Accept(Socket client);

protected Task Handle(Socket client, Stream inputStream)
protected async Task Handle(Socket client, Stream inputStream)
{
inputStream.ReadTimeout = (int)Configuration.RequestReadTimeout.TotalMilliseconds;
return new ClientHandler(client, inputStream, Server, this, Configuration).Run();

await new ClientHandler(client, inputStream, Server, this, Configuration).Run().ConfigureAwait(false);
}

#endregion
Expand Down
6 changes: 3 additions & 3 deletions Core/GenHTTP.Core/Infrastructure/Endpoints/SecureEndPoint.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,11 @@ internal SecureEndPoint(IServer server, IPEndPoint endPoint, SecurityConfigurati

protected override async Task Accept(Socket client)
{
var stream = await TryAuthenticate(client);
var stream = await TryAuthenticate(client).ConfigureAwait(false);

if (stream != null)
{
await Handle(client, stream);
await Handle(client, stream).ConfigureAwait(false);
}
else
{
Expand All @@ -77,7 +77,7 @@ protected override async Task Accept(Socket client)
{
var stream = new SslStream(new NetworkStream(client), false);

await stream.AuthenticateAsServerAsync(AuthenticationOptions, CancellationToken.None);
await stream.AuthenticateAsServerAsync(AuthenticationOptions, CancellationToken.None).ConfigureAwait(false);

return stream;
}
Expand Down
46 changes: 22 additions & 24 deletions Core/GenHTTP.Core/Protocol/ClientHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ internal async Task Run()
{
try
{
await HandlePipe(PipeReader.Create(Stream, READER_OPTIONS));
await HandlePipe(PipeReader.Create(Stream, READER_OPTIONS)).ConfigureAwait(false); ;
}
catch (Exception e)
{
Expand Down Expand Up @@ -92,7 +92,7 @@ private async Task HandlePipe(PipeReader reader)

RequestBuilder? request;

while ((request = await parser.TryParseAsync(buffer)) != null)
while ((request = await parser.TryParseAsync(buffer).ConfigureAwait(false)) != null)
{
if (!await HandleRequest(request))
{
Expand All @@ -102,42 +102,40 @@ private async Task HandlePipe(PipeReader reader)
}
finally
{
await reader.CompleteAsync();
await reader.CompleteAsync().ConfigureAwait(false);
}
}

private async ValueTask<bool> HandleRequest(RequestBuilder builder)
{
var address = ((IPEndPoint)Connection.RemoteEndPoint).Address;

using (var request = builder.Connection(Server, EndPoint, address).Build())
using var request = builder.Connection(Server, EndPoint, address).Build();

if (KeepAlive == null)
{
if (KeepAlive == null)
{
KeepAlive = request["Connection"]?.Equals("Keep-Alive", StringComparison.InvariantCultureIgnoreCase) ?? false;
}

bool keepAlive = (bool)KeepAlive;
KeepAlive = request["Connection"]?.Equals("Keep-Alive", StringComparison.InvariantCultureIgnoreCase) ?? false;
}

var responseHandler = new ResponseHandler(Server, Stream, Configuration);
var requestHandler = new RequestHandler(Server);
bool keepAlive = (bool)KeepAlive;

using (var response = requestHandler.Handle(request, out Exception? error))
{
var success = await responseHandler.Handle(request, response, keepAlive, error);
var responseHandler = new ResponseHandler(Server, Stream, Configuration);
var requestHandler = new RequestHandler(Server);

if (!success || !keepAlive)
{
Connection.LingerState = LINGER_OPTION;
Connection.Disconnect(false);
Connection.Close();
using var response = requestHandler.Handle(request, out Exception? error);

var success = await responseHandler.Handle(request, response, keepAlive, error).ConfigureAwait(false);

return false;
}
if (!success || !keepAlive)
{
Connection.LingerState = LINGER_OPTION;
Connection.Disconnect(false);
Connection.Close();

return true;
}
return false;
}

return true;
}

#endregion
Expand Down
2 changes: 1 addition & 1 deletion Core/GenHTTP.Core/Protocol/RequestBuffer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ internal RequestBuffer(PipeReader reader, NetworkConfiguration configuration)

try
{
Data = (await Reader.ReadAsync(cancellation.Token)).Buffer;
Data = (await Reader.ReadAsync(cancellation.Token).ConfigureAwait(false)).Buffer;
}
catch (OperationCanceledException)
{
Expand Down
4 changes: 2 additions & 2 deletions Core/GenHTTP.Core/Protocol/RequestContentParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ internal async Task<Stream> GetBody(RequestBuffer buffer)

while (toFetch > 0)
{
await buffer.Read();
await buffer.Read().ConfigureAwait(false);

var toRead = Math.Min(buffer.Data.Length, Math.Min(Configuration.TransferBufferSize, toFetch));

Expand All @@ -49,7 +49,7 @@ internal async Task<Stream> GetBody(RequestBuffer buffer)

while (data.TryGet(ref position, out var memory))
{
await body.WriteAsync(memory);
await body.WriteAsync(memory).ConfigureAwait(false);
}

buffer.Advance(toRead);
Expand Down
18 changes: 9 additions & 9 deletions Core/GenHTTP.Core/Protocol/RequestParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ internal RequestParser(NetworkConfiguration configuration)
{
string? method, path, protocol;

if ((method = await TryReadToken(buffer, ' ')) != null)
if ((method = await TryReadToken(buffer, ' ').ConfigureAwait(false)) != null)
{
Request.Type(method);
}
Expand All @@ -45,7 +45,7 @@ internal RequestParser(NetworkConfiguration configuration)
return null;
}

if ((path = await TryReadToken(buffer, ' ')) != null)
if ((path = await TryReadToken(buffer, ' ').ConfigureAwait(false)) != null)
{
Request.Path(path);
}
Expand All @@ -54,7 +54,7 @@ internal RequestParser(NetworkConfiguration configuration)
return null;
}

if ((protocol = await TryReadToken(buffer, '\r', 1, 5)) != null)
if ((protocol = await TryReadToken(buffer, '\r', 1, 5).ConfigureAwait(false)) != null)
{
Request.Protocol(protocol);
}
Expand All @@ -63,9 +63,9 @@ internal RequestParser(NetworkConfiguration configuration)
return null;
}

while (await TryReadHeader(buffer, Request)) { /* nop */ }
while (await TryReadHeader(buffer, Request).ConfigureAwait(false)) { /* nop */ }

if (await TryReadToken(buffer, '\r', 1) == null)
if ((await TryReadToken(buffer, '\r', 1).ConfigureAwait(false)) == null)
{
return null;
}
Expand All @@ -78,7 +78,7 @@ internal RequestParser(NetworkConfiguration configuration)
{
var parser = new RequestContentParser(length, Configuration);

Request.Content(await parser.GetBody(buffer));
Request.Content(await parser.GetBody(buffer).ConfigureAwait(false));
}
}
else
Expand All @@ -97,9 +97,9 @@ private async ValueTask<bool> TryReadHeader(RequestBuffer buffer, RequestBuilder
{
string? key, value;

if ((key = await TryReadToken(buffer, ':', 1)) != null)
if ((key = await TryReadToken(buffer, ':', 1).ConfigureAwait(false)) != null)
{
if ((value = await TryReadToken(buffer, '\r', 1)) != null)
if ((value = await TryReadToken(buffer, '\r', 1).ConfigureAwait(false)) != null)
{
request.Header(key, value);
return true;
Expand All @@ -115,7 +115,7 @@ private async ValueTask<bool> TryReadHeader(RequestBuffer buffer, RequestBuilder

if (position == null)
{
if (await buffer.Read(true) == null)
if ((await buffer.Read(true).ConfigureAwait(false)) == null)
{
return null;
}
Expand Down
Loading

0 comments on commit 1794d57

Please sign in to comment.