Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

C# Dictionary

  1. Home
  2. C# Dictionary
  3. Task.FromResult() / CancellationToken

Task.FromResult() / CancellationToken

How to use Task.FromResult() to create a Task with an already-determined result, and CancellationToken to cancel asynchronous operations.

Syntax

using System;
using System.Threading;
using System.Threading.Tasks;

// Creates an already-completed Task<TResult> (completes immediately, no await needed).
Task<TResult> task = Task.FromResult<TResult>(result);

// Creates the sender (CancellationTokenSource) that issues cancellation requests.
CancellationTokenSource cts = new CancellationTokenSource();

// Gets the receiver (CancellationToken) to pass to async methods.
CancellationToken token = cts.Token;

// Requests cancellation (calling Cancel() sets token.IsCancellationRequested to true).
cts.Cancel();

// Throws OperationCanceledException if cancellation has been requested.
token.ThrowIfCancellationRequested();

Method List

Method / PropertyDescription
Task.FromResult(result)Returns an already-completed Task<TResult> with the specified value as its result.
Task.CompletedTaskReturns an already-completed Task with no return value. Use this as an alternative to Task.FromResult(0).
CancellationTokenSource.Cancel()Issues a cancellation request. Sets IsCancellationRequested on the Token to true.
CancellationTokenSource.CancelAfter(ms)Automatically issues cancellation after the specified number of milliseconds. Use this for timeout handling.
CancellationToken.IsCancellationRequestedReturns true if cancellation has been requested.
CancellationToken.ThrowIfCancellationRequested()Throws OperationCanceledException if cancellation has been requested.

Sample Code

using System;
using System.Threading;
using System.Threading.Tasks;

class Program
{
    // Example use of Task.FromResult() — useful for synchronous interface implementations.
    static Task<int> GetCachedValueAsync(bool useCache)
    {
        if (useCache)
        {
            // Use Task.FromResult() to return a cached value immediately.
            return Task.FromResult(42);
        }
        return Task.Run(() => 42); // Actual async processing
    }

    // An async method that accepts a CancellationToken.
    static async Task LongRunningTaskAsync(CancellationToken token)
    {
        for (int i = 1; i <= 5; i++)
        {
            // Throws OperationCanceledException if cancellation was requested.
            token.ThrowIfCancellationRequested();

            Console.WriteLine($"Processing... {i}/5");
            await Task.Delay(500, token); // Pass the token to Delay as well.
        }
        Console.WriteLine("Processing complete");
    }

    static async Task Main()
    {
        // Task.FromResult() example.
        int result = await GetCachedValueAsync(true);
        Console.WriteLine($"Cached value: {result}");

        // CancellationToken example — automatically cancels after 2 seconds.
        using CancellationTokenSource cts = new CancellationTokenSource();
        cts.CancelAfter(1200); // Cancels after 1.2 seconds.

        try
        {
            await LongRunningTaskAsync(cts.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was cancelled.");
        }
    }
}

Notes

Task.FromResult() is useful when an interface requires a method signature that returns Task<T>, but you want to return a value synchronously. For methods with no return value, use Task.CompletedTask instead.

Always wrap CancellationTokenSource in a using block or call Dispose() to release its resources. You cannot reuse a CancellationTokenSource after cancellation has been requested. Create a new instance each time you need a cancellable operation. For the basics of asynchronous programming, see async / await. For task execution and delays, see Task.Run() / Task.Delay().

If you find any errors or copyright issues, please .