public void Shutdown() { try { Dictionary <string, CancellationTokenSource> .Enumerator sourceEn = sources.GetEnumerator(); while (sourceEn.MoveNext()) { try { CancellationTokenSource cts = sourceEn.Current.Value; cts.Cancel(); } catch { } } sources.Clear(); Dictionary <string, VirtualRtuAdapter> .Enumerator adapterEn = adapters.GetEnumerator(); while (adapterEn.MoveNext()) { try { VirtualRtuAdapter adapter = adapterEn.Current.Value; adapter.Dispose(); } catch { } } adapters.Clear(); } catch { } listener.Stop(); }
public async Task RunAsync() { listener = new TcpListener(new IPEndPoint(GetIPAddress(System.Net.Dns.GetHostName()), 502)); listener.ExclusiveAddressUse = false; listener.Start(); while (true) { try { TcpClient tcpClient = await listener.AcceptTcpClientAsync(); tcpClient.LingerState = new LingerOption(true, 0); tcpClient.NoDelay = true; tcpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); CancellationTokenSource cts = new CancellationTokenSource(); IChannel channel = ChannelFactory.Create(false, tcpClient, 1024, 1024 * 100, cts.Token); RtuMap map = await RtuMap.LoadAsync(config.RtuMapSasUri); //load RTU map so always up to date. VirtualRtuAdapter adapter = new VirtualRtuAdapter(map, channel); adapters.Add(adapter.Id, adapter); sources.Add(adapter.Id, cts); adapter.OnError += Adapter_OnError; adapter.OnClose += Adapter_OnClose; await adapter.StartAsync(); } catch (Exception ex) { OnError?.Invoke(this, new ListenerErrorEventArgs(ex)); } } }