.NET API Reference

System
ITaskCompletion
Represents a task that can be completed. This interface is a fundamental building block for asynchronous operations in .NET, allowing for the observation and manipulation of task state. It's often implemented by types that manage the outcome of an operation that may take some time to finish.

Summary

The ITaskCompletion interface defines a contract for objects that represent the result of an asynchronous operation. It provides methods to check if the operation has completed, retrieve its result, and handle any exceptions that may have occurred. This interface is crucial for writing non-blocking code and managing the flow of concurrent operations.

Members

Name Type Description
GetAwaiter() IAwaiter Returns an awaiter for the task.
IsCompleted bool Gets a value indicating whether the task has completed.
GetResult() object Gets the result of the task.
Result object Gets the result of the task.
Exception Exception Gets the exception information, if the asynchronous operation completed synchronously with an exception.

Member Details

GetAwaiter()

Returns an awaiter for the task. This is the primary mechanism used by the await keyword in C# to asynchronously wait for the task to complete.

Syntax

IAwaiter GetAwaiter();

Returns

An IAwaiter object that can be used to await the completion of the task.

IsCompleted

Gets a value indicating whether the task has completed. This property can be checked to determine if the result is available or if any exceptions have been thrown.

Syntax

bool IsCompleted { get; }

Property Value

true if the task has completed; otherwise, false.

GetResult()

Retrieves the result of the completed task. If the task completed with an exception, this method will re-throw that exception.

Syntax

object GetResult();

Returns

The result of the task. This is a non-generic object and should be cast to the expected type.

Exceptions

AggregateException: The asynchronous operation completed synchronously with an exception.

Result

A convenient property to access the result of the task. Similar to GetResult(), it will throw an exception if the task failed.

Syntax

object Result { get; }

Property Value

The result of the task.

Exception

Provides access to the exception if the task completed synchronously with an error. This is useful for inspecting the error without necessarily completing the task flow.

Syntax

Exception Exception { get; }

Property Value

The Exception object representing the error, or null if no exception occurred.

Example Usage

Basic Asynchronous Operation

This example demonstrates how to use ITaskCompletion with the await keyword.

using System;
using System.Threading.Tasks;

public interface ITaskCompletion {
    IAwaiter GetAwaiter();
    bool IsCompleted { get; }
    object GetResult();
    object Result { get; }
    Exception Exception { get; }
}

public interface IAwaiter {
    bool IsCompleted { get; }
    void OnCompleted(Action action);
    object GetResult();
}

public class MyTask : ITaskCompletion {
    // Simplified implementation for demonstration
    private bool _isCompleted = false;
    private object _result;
    private Exception _exception;

    public MyTask(object result) {
        _result = result;
        _isCompleted = true;
    }

    public MyTask(Exception ex) {
        _exception = ex;
        _isCompleted = true;
    }

    public IAwaiter GetAwaiter() {
        return new MyAwaiter(this);
    }

    public bool IsCompleted { get { return _isCompleted; } }
    public object Result { get { return GetResult(); } }
    public Exception Exception { get { return _exception; } }

    object ITaskCompletion.GetResult() {
        if (_exception != null) {
            throw _exception;
        }
        return _result;
    }

    private class MyAwaiter : IAwaiter {
        private readonly MyTask _task;

        public MyAwaiter(MyTask task) {
            _task = task;
        }

        public bool IsCompleted { get { return _task.IsCompleted; } }

        public void OnCompleted(Action action) {
            // In a real scenario, this would involve registering a callback
            if (_task.IsCompleted) {
                action?.Invoke();
            }
        }

        object IAwaiter.GetResult() {
            return _task.GetResult();
        }
    }
}

public static class Program {
    public static void Main(string[] args) {
        // Simulate an async operation
        ITaskCompletion task = new MyTask("Operation completed successfully!");

        if (task.IsCompleted) {
            try {
                string result = (string)task.Result;
                Console.WriteLine(result);
            } catch (Exception ex) {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }

        // In a real async method context:
        // var result = await GetSomeDataAsync();
        // Console.WriteLine(result);
    }
}