简体   繁体   中英

Update Collection with multithreading and WPF

At the moment I have a class for scanning the network:

public class Network {
   public event NewDeviceHandler NewDevice;
   public event ScanFinishedHandler ScanFinished;
   //...
   public void Scan() { /* ... */ }
}

I want to update my UI as soon as a new Device was found. What is the best practice in this case? Should I use events or is it better to use something like an ObservableCollection?

And I have to call this method in my UI-Thread (WPF). How should I do that?

  • Create a new Task in my UI-Application
  • Create a new Task in the Scan-Method
  • Use asnyc / await

Thank you very much for your help.

If you want to update your UI as soon as a new Device was found, you will only need ObservableCollection and Task . For example:

In Network class:

public event NewDeviceHandler<Device> NewDevice;

public void  StartScan()
{
    Task.Run(() => Scan() );
}

In view-model:

public ObservableCollection<Device> DevicesCollection { get; set; }

In code-behind:

private Network networkService = new Network();
...
// Somewhere in initialization code:
networkService.NewDevice += (sender, device) => Dispatcher.Invoke(() => viewModel.DevicesCollection.Add(device) );
...
private void ScanButton_OnClick(object sender, RoutedEventArgs e)
{
    viewModel.DevicesCollection.Clear();
    networkService.StartScan();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM