private async void ScanAsync(CancellationToken token) { try { IsRunning = true; _results.Clear(); using (var master = ModbusAdapters.GetFactory().Create()) { try { var stream = master.Master.Transport.GetStreamResource(); stream.DiscardInBuffer(); } catch (Exception ex) { Console.WriteLine(ex); } ProgressValue = 0; ProgressMax = (byte)(EndAddress - StartAddress); for (byte slaveAddress = StartAddress; slaveAddress < EndAddress; slaveAddress++) { CurrentSlaveAddress = slaveAddress; if (token.IsCancellationRequested) { break; } bool wasFound = false; string reason; try { await master.Master.ReadHoldingRegistersAsync(slaveAddress, 1000, 1); reason = "Reading Holding Register succeeded."; wasFound = true; } catch (TimeoutException ex) { reason = ex.Message; //Not found } catch (SlaveException ex) { //We got sopme sort of slave exception. reason = ex.Message; wasFound = true; } catch (Exception ex) { reason = ex.Message; } //Create the result. var result = new ResultViewModel() { SlaveAddress = slaveAddress, WasFound = wasFound, Reason = reason, }; _results.Add(result); ProgressValue++; } } if (_results.Count != 0) { string message; var successfulCount = _results.Count(r => r.WasFound); if (successfulCount == 0) { message = "No Modbus slaves were found."; } else if (successfulCount == 1) { message = "1 Modbus slave was found."; } else { message = $"{successfulCount} Modbus slaves were found."; } MessageBox.Show(message, "Scan Result"); } } catch (Exception ex) { MessageBox.Show(ex.Message); } IsRunning = false; _cts = null; CommandManager.InvalidateRequerySuggested(); }