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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With