From bc60542011430d4ab15164faa5f94b192f53ba98 Mon Sep 17 00:00:00 2001 From: "Alecio Furanze (Ale)" Date: Sun, 23 Jun 2024 11:53:56 +0200 Subject: [PATCH] make HTTP.Server be async instead of sync --- src/http/partials/Server/HTTP.ServerTo.cs | 63 +++++++++-------------- 1 file changed, 24 insertions(+), 39 deletions(-) diff --git a/src/http/partials/Server/HTTP.ServerTo.cs b/src/http/partials/Server/HTTP.ServerTo.cs index ca712619..f7adf84f 100644 --- a/src/http/partials/Server/HTTP.ServerTo.cs +++ b/src/http/partials/Server/HTTP.ServerTo.cs @@ -54,7 +54,7 @@ public Task Open(Uri host) _server._serverOn.OnOpen?.Invoke(null, null); - ReceiveRequests(); + InitAccept(); } catch (Exception e) { @@ -150,50 +150,35 @@ public void WebsocketEventBroadcast(string name, string data, Encoding encoding) } } - private void ReceiveRequests() + private void InitAccept() { - var thread = new Thread(() => + _listener.BeginGetContext(AcceptCallback, null); + + void AcceptCallback(IAsyncResult result) { - while (IsOpened) + if (IsOpened) { - HttpListenerContext context = null; - NetlyEnvironment.Logger.Create("Request entry."); + HttpListenerContext context = _listener.EndGetContext(result); - try - { - context = _listener.GetContext(); - } - catch (Exception e) + Task.Run(async () => { - context = null; - NetlyEnvironment.Logger.Create($"Request fail: {e}"); - } - finally - { - if (context != null) - Task.Run(() => - { - NetlyEnvironment.Logger.Create("Task Init"); - - try - { - var task = HandleConnection(context); - Task.WaitAll(task); - } - catch (Exception e) - { - NetlyEnvironment.Logger.Create($"Task error: {e}"); - } - - NetlyEnvironment.Logger.Create("Task End"); - }); - } + try + { + await HandleConnection(context); + } + catch (Exception e) + { + NetlyEnvironment.Logger.Create($"{this}: {e}"); + } + }); + + InitAccept(); } - - Close(); - }) { IsBackground = true }; - - thread.Start(); + else + { + Close(); + } + } }