How to handle async cancellations in Blazor Server-Side Applications

Viewed 229

I am just not sure what is the correct way to handle cancellations of async requests.

I have a method on a page that calls three long running async tasks one after the other. If user navigates from the page, I am assuming that these tasks generate exceptions of type TaskCanceledException. Is it okay to catch these specific exceptions in the catch block, restore the state to proper state so that user can continue to use the system? Will those async tasks be automatically canceled or do I need to pass cancellation tokens to async methods and then explicitly call the cancel method of those tokens?

method with try/catch:

public void RefreshProject()
{           
   try
   {
      await LongRunningTask1();
      await LongRunningTask2();
      await LongRunningTask3();
   }
   catch (Exception ex)
   {
     //restore proper state
   }
}

method with cancellationtokensource:

public void RefreshProject()
{  
   CancellationTokenSource cts1 = new CancellationTokenSource();
   CancellationTokenSource cts2 = new CancellationTokenSource();
   CancellationTokenSource cts3 = new CancellationTokenSource();         

   try
   {
      await LongRunningTask1(cts1);
      cts1.Token.ThrowIfCancellationRequested();
      await LongRunningTask2(cts2);
      cts2.Token.ThrowIfCancellationRequested();
      await LongRunningTask3(cts3);
      cts3.Token.ThrowIfCancellationRequested();
   }
   catch (Exception ex)
   {
     //restore proper state
     //application specific logic
     //cancel async tasks
     cts1.Cancel();
     cts2.Cancel(); 
     cts3.Cancel();  
   }
}

or do I need to inherit from IDisposable and cancel tasks in Dispose method?

Which one is the correct method in my case? Any suggestions/patterns?

0 Answers
Related