How to use CanellationToken With ICommand A Solid Implementation of ICommand

Ahmed Fouad
Nov 15 · 1 min read

This article can be considered a part 2 of Async Command A Modern Implementation of ICommand in which we were addressing the async problem in ICommand by blocking the CanExecuteStatus to false in case the previous task was not yet completed.

In this article, we will address the same problem using a different way we will use CancellationToken to cancel the pending task and execute the new one, imagine you have a news app where the user should click on one title in a listview the app will download the news article and will show it, what happens when the user clicks on a title and before the download complete he clicks on another one.

And you can use it in your ViewModel like this

CommandAsync<Uri> commandAsync = new CommandAsync<Uri>(async (uri,cancellationToken)=>await client.GetAsync(uri,cancellationToken));

or can be simplified to this

CommandAsync<Uri> commandAsync = new CommandAsync<Uri>(httpclient.GetAsync);

Written by

Hello, I’m Ahmed. I’m a software engineer living in Vienna, Austria. I am a fan of technology, web development, and programming. I’m also interested in xamarin

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade