I've got an ObservableCollection<string>
binded to a WPF view. There is a method that refreshs the content of the collection. This method is processing in a background thread and takes a few seconds. To avoid errors, the called method is synchronized.
It may happen, that the method is called, even if the previous processing has not finished. In that case, I would like to stop the current processing and start the new one.
private ObservableCollection<string> col = new ObservableCollection<string>();
private async void Refresh()
{
var ui = TaskScheduler.FromCurrentSynchronizationContext();
await Task.Factory.StartNew(() =>
{
return GetNewObjects();
}).ContinueWith(t =>
{
col = t.Result;
}, ui);
}
[MethodImpl(MethodImplOptions.Synchronized)]
private ObservableCollection<string> GetNewObjects()
{
// processing
}
My idea is to save a reference of the corresponding Task
in Refresh() and check in every call, if there is already a running task. Is that the right (and safe) way to stop a task?