public async Task ScanAsync() { _cts.Cancel(); Devices.Clear(); try { var cts = new CancellationTokenSource(); _cts = cts; String strHostName = Dns.GetHostName(); // Find host by name IPHostEntry iphostentry = Dns.GetHostEntry(strHostName); // Enumerate IP addresses List <Task> tasks = new List <Task>(); foreach (IPAddress ipaddress in iphostentry.AddressList) { if (ipaddress.AddressFamily == AddressFamily.InterNetwork) { Task discoveryTask = DeviceDiscovery.DiscoveryAsync(cts.Token, ipaddress); tasks.Add(discoveryTask); } } foreach (Task discoveryTask in tasks) { await discoveryTask; } cts.Dispose(); } catch (Exception e) { MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }
public async Task ScanAsync() { if (discoveryTask != null && (discoveryTask.Status == TaskStatus.WaitingForActivation || discoveryTask.Status == TaskStatus.Running)) { _cts.Cancel(); Devices.Clear(); } try { var cts = new CancellationTokenSource(); _cts = cts; discoveryTask = DeviceDiscovery.DiscoveryAsync(_cts.Token).ContinueWith((t) => cts.Dispose()); await discoveryTask; } catch (Exception e) { MessageBox.Show(e.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); } }