Canceling Long Running Task using Cancellation Token | How to Create Synchronous Method using Task
Canceling Long Running Task using Cancellation Token | How to Create Synchronous Method using Task | Dot Net Tutorials | Pranaya Rout Text Document Link: Canceling Long Running Task using Cancellation Token: https://dotnettutorials.net/lesson/how-to-cancel-a-task-in-csharp/ How to Create Synchronous Method using Task in C#: https://dotnettutorials.net/lesson/how-to-create-synchronous-method-using-task-in-csharp/ How to Cancel a Long-Running Task in C#? When we run a long task, providing our users with some mechanism to cancel the task is a good practice. The .NET Framework provides a Cancellation Token, using which we can cancel a task. How to Create Synchronous Method using Task in C#? There will be occasions when you will have a method with an asynchronous signature, that is, return Task, but its implementation will be Synchronous. One reason for this is that you have to implement a basic interface that returns a task, and the implementation is synchronous. Another reason could be that you need to mock asynchronous methods in your unit tests. And the implementation is going to be synchronous. To solve these problems, we can use axillary methods like CompletedTask, FromResult, FromException, and FromCanceled. With Task.CompletedTask method: We can implement a method that returns a task, but that is synchronous. With Task.FromResult method, we can implement a method that is Task of T, which is synchronous. And, of course, we can return a value that will be wrapped inside of a task. With Task.FromException, we can create a task that is completed with an error. With Task.FromCanceled, we can create a task that has been canceled. It is important to be able to create a task that has an Exception or that is Canceled because of your unit tests; you may want to test a method that has to handle a faulted task, a task with an exception, or a task that has been canceled.