public static void RemoveAction(this HttpListener listener, Delegate action) { var key = listener.GetHashCode(); if (received_actions.ContainsKey(key)) { var temp = Delegate.RemoveAll(received_actions[key], action); received_actions[key] = temp; } }
public static void ClearActions(this HttpListener listener) { var key = listener.GetHashCode(); if (received_actions.TryRemove(key, out Delegate r)) { r = null; } if (task_tokens.TryRemove(key, out CancellationTokenSource t)) { t.Cancel(); t.Dispose(); } }
public static void WhenReceived(this HttpListener listener, Action <HttpListenerContext> action) { if (action == null) { throw new ArgumentNullException(); } var key = listener.GetHashCode(); if (!received_actions.ContainsKey(key)) { received_actions[key] = action; } else { var temp = Delegate.Combine(received_actions[key], action); received_actions[key] = temp; } if (task_tokens.ContainsKey(key)) { return; } var context = SynchronizationContext.Current; var cts = new CancellationTokenSource(); Task.Run(async() => { while (true) { if (cts.IsCancellationRequested) { break; } var httpContext = await listener.GetContextAsync(); if (received_actions.ContainsKey(key)) { context.Post(_ => { received_actions[key].DynamicInvoke(httpContext); }, null); } } }, cts.Token).ConfigureAwait(false); task_tokens[key] = cts; }