public static void RemoveAction(this TcpListener listener, Delegate action) { try { var key = listener.GetHashCode(); if (tcp_connected_actions.ContainsKey(key)) { var temp = Delegate.RemoveAll(tcp_connected_actions[key], action); tcp_connected_actions[key] = temp; } } catch { } }
public static void WhenConnected(this TcpListener listener, Action <TcpClient> action) { if (action == null) { throw new ArgumentNullException(); } var key = listener.GetHashCode(); if (tcp_connected_actions.ContainsKey(key)) { var temp = Delegate.Combine(tcp_connected_actions[key], action); tcp_connected_actions[key] = temp; } else { tcp_connected_actions[key] = action; } if (task_tokens.ContainsKey(key)) { return; } var cts = new CancellationTokenSource(); var context = SynchronizationContext.Current; Task.Run(async() => { while (true) { try { if (cts.IsCancellationRequested) { break; } var client = await listener.AcceptTcpClientAsync(); if (tcp_connected_actions.ContainsKey(key)) { var a = tcp_connected_actions[key]; context.Post(_ => { a.DynamicInvoke(client); }, null); } } catch { break; } } }, cts.Token).ConfigureAwait(false); task_tokens[key] = cts; }
public static void ClearActions(this TcpListener listener) { try { var key = listener.GetHashCode(); Delegate a; if (tcp_connected_actions.TryRemove(key, out a)) { a = null; } CancellationTokenSource t; if (task_tokens.TryRemove(key, out t)) { t.Cancel(); t.Dispose(); } } catch { } }