Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of Task.FromCanceled

Tags:

c#

.net

I'm new to TPL, and confused with the purpose of Task's static FromXXX methods:

public class Task : ... 
{
   public static Task FromCanceled(CancellationToken cancellationToken);
   public static Task FromException(Exception exception);
   public static Task<TResult> FromResult<TResult>(TResult result);
}

Let's take Task.FromCanceled for example, why do we need this one? When we create a Task, we want to execute something, so what's the purpose of creating an canceled task that won't ever do anything?


1 Answers

Here's an example. You have a library that declares a method as returning Task, with a view of using async/await:

public interface IFoo
{
    Task BarAsync(CancellationToken token);
}

But your code / unit test method is synchronous and has nothing to await, so we can therefore implement it with Task.FromResult, etc.

public class MyFoo : IFoo
{
    public Task BarAsync(CancellationToken cancellationToken)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            return Task.FromCanceled(cancellationToken);
        }
        return Task.CompletedTask;
    }
}

Note that you can also find examples of things like this in the wild. GitHub search

For example, this code uses it in a similar scenario to what I described above.

like image 159
DiplomacyNotWar Avatar answered Sep 07 '25 15:09

DiplomacyNotWar