public void OpenLink() { switch (linkViewModel.SelectedLinkType) { case TypeOfLink.COM: if (linkViewModel.SelectedComPort == null || linkViewModel.SelectedComPort == string.Empty) { Message(this, new MessageDataEventArgs() { MessageString = "Не выбран COM порт", MessageType = MessageType.Warning }); return; } Link = new LinkCOM(linkViewModel.SelectedComPort); ((LinkCOM)Link).Message += messageInputHandler; Link.Connected += mainVM.Link_Connected; Link.Disconnected += mainVM.Link_Disconnected; Link.Connect(); break; case TypeOfLink.TCP: var tcpLink = new LinkTCP(); tcpLink.IPAddress = mainVM.VM_Link.IP_Address; tcpLink.PortNumber = mainVM.VM_Link.TCP_Port; tcpLink.Message += messageInputHandler; tcpLink.Connected += mainVM.Link_Connected; tcpLink.Disconnected += mainVM.Link_Disconnected; Link = tcpLink; Link.Connect(); break; case TypeOfLink.GSM: if (linkViewModel.SelectedComPort == null || linkViewModel.SelectedComPort == string.Empty) { Message(this, new MessageDataEventArgs() { MessageString = "Не выбран COM порт", MessageType = MessageType.Warning }); return; } Link = new LinkGSM(); ((LinkGSM)Link).ComPort = linkViewModel.SelectedComPort; ((LinkGSM)Link).PhoneNumber = linkViewModel.PhoneNumber; ((LinkGSM)Link).Message += messageInputHandler; Link.Connected += mainVM.Link_Connected; Link.Disconnected += mainVM.Link_Disconnected; //((LinkGSM)Link).Initialize(); Link.LinkDelay = 10000; Link.Connect(); break; default: break; } }
public void Subscribe(Action <T> receiver) { lock (_sync) { _link.Connect(); _cancellation = new CancellationTokenSource(); var token = _cancellation.Token; _readerThread = new Thread(() => { while (!token.IsCancellationRequested) { try { var header = _link.Read(typeof(SimpleHeaderMessage)) as SimpleHeaderMessage; var type = Type.GetType(header.TypeName); var message = (T)_link.Read(type); try { _q.Add( new Packate <SimpleHeaderMessage, T> { Header = header, Message = message }, token); } catch (OperationCanceledException) { break; } } catch (Exception e) { if (!token.IsCancellationRequested) { Console.WriteLine("error:subs-reader: " + e); Reconnect(); } } } }) { IsBackground = true, Name = "subs-reader" }; _readerThread.Start(); _consumerThread = new Thread(() => { while (!token.IsCancellationRequested) { try { try { var package = _q.Take(token); receiver(package.Message); } catch (OperationCanceledException) { break; } } catch (Exception e) { Console.WriteLine("error:subs-consumer " + e); } } }) { IsBackground = true, Name = "subs-consumer" }; _consumerThread.Start(); } }