How to cancel previous invocations of a longer-running async call in Blazor?

Viewed 321

As I try to build a GUI with Blazor that is snappy and always responds to user input, it may come about that some longer-running async operation might get invoked multiple times, often before the first invocation has finished. Now I imagine there might be a way for the second invocation to cancel the first, but it would seem to take ugly CancellationTokenSource code.

Is there any easier way in Blazor to set up certain asynchronous calls to fail/terminate early if they are invoked again before completion? This would seem to be a need that many would have, but I'm not even sure how to Google-search it. Something like the following (which I realize is unsound for a few reasons):

public Task? pendingLoadTask = null;

public async Task Load(){
    pendingLoadTask = httpClient.GetAsync("/api/customers");
    Customers = await pendingLoadTask.CancelOnSubsequentRun();
}

public static Task<T> CancelOnSubsequentRun<T>(this Task<T> task){
   await task... //somehow cancel the pending load task
}

I am mostly curious if there is some more elegant way than peppering every async call with different cancellation tokens.

0 Answers
Related