I need to implement async
task cancel. I know that CancellationTokenSource
would help me in achieving that. But I'm unable to find a proper way.
I have a search textbox, whenever a user types in textbox, for each textchanged event I call GetStocks
method as shown below,
public async Task GetStocks()
{
var stockings = new List<Services.Models.Admin.SiteStockingLevelsModel>();
IsBusy = true;
cts?.Cancel();
cts = new CancellationTokenSource();
await Task.Run(() => { CreateStockingCollection(); });
ValidateMaterials();
IsBusy = false;
}
The CreateStockingCollection
method is as shown below,
private void CreateStockingCollection()
{
var stockings = _siteStockingLevelsService.GetSiteInventoryLevels(SiteId);
CreateStockingLevelCompareCollection(stockings);
StockingLevels =
_mapper.Map<TrulyObservableCollection<SiteStockingLevelsModel>>(stockings);
((INotifyPropertyChanged)StockingLevels).PropertyChanged +=
(x, y) => CompareStockingChanges();
CompareStockingChanges();
}
My requirement here is,
Example Suppose user wants to type "Abc". When user types "A" the GetStocks
method will be called, immediately the user enters "b" the again the get stocks methods will be called, in this case i want to cancel the previous GetStocks
task called with letter "A".