I am using a Task to read some data from the Database etc. Let's assume I can't change the Dataaccess-API/-Layer.
This dataaccess might sometimes need some time (network-traffic etc.). It will be loaded everey time a user changes a selected item or changes the filter that shows a subset of the aviable data.
At the end I have a little example of my Task-Start-Method.
My Question is: If the user changes the filter/selection while the task is still running, how can I stop it from running? When using the cancellation token it will finish (as I am not using a "big" loop in the task, I can't just check every iteration for .IsCancelled
.
My idea was to use the return type of the Task to fill the SelectableVolts
and check the returning Task on IsCancelled
before assigning the new value. But how to do this for an async Task?
// added code at the bottom of this question
UPDATE: After getting comments like "I am not totally sure what your question is asking for, but this should help you get a feel for some avalible options." I will try to clarify my problem a little bit. At least I hope so ;)
- User selects object in datagrid
- ViewModel needs data and asks method/class/foo for data.
- Task(A) is started
- Task(A) is still working. User selects different object/row.
- Steps 1, 2 and 3 are repeated. So Task(A) should be cancelled/stopped and a new Task(B) starts.
- When Task(B) is finished its data should be displayed. In no way Task(A)s data should be made available.
So the question is: How to achieve steps 5 and 6 in a correct way.
Full Code:
private CancellationToken cancelTokenOfFilterTask;
private CancellationTokenSource cancelTokenSourceOfFilterTask;
private void FilterVolts()
{
if (IsApplicationWorking)
{
cancelTokenSourceOfFilterTask.Cancel();
}
// Prepare CancelToken
cancelTokenSourceOfFilterTask = new CancellationTokenSource();
cancelTokenOfFilterTask = cancelTokenSourceOfFilterTask.Token;
IsApplicationWorking = true;
if (SelectableVolts != null && SelectableVolts.Count >= 0)
{
VoltThatIsSelected = null;
SelectableVolts.Clear();
}
Task voltLoadTask = null;
voltLoadTask = Task.Factory.StartNew<List<SelectableVoltModel>>(() => {
VoltsLoader loader = new VoltsLoader();
Thread.Sleep(2000);
var listOfVolts = loader.LoadVoltsOnFilter(_sourceOfCachableData, ChosenFilter);
return listOfVehicles;
}, cancelTokenOfFilterTask).ContinueWith(listSwitcher =>
{
switch (listSwitcher.Status)
{
case TaskStatus.RanToCompletion:
SelectableVolts = new ObservableCollection<SelectableVoltsModel>(listSwitcher.Result);
IsApplicationWorking = false;
break;
case TaskStatus.Canceled:
Console.WriteLine("Cancellation seen"); // Gets never called
break;
default:
break;
}
});
}
Somehow when I call this Method more than once, all will run in TaskStatus.RanTocompletion
how can this be possible? Am I doing someting wrong with the cancel-token?