Windows.Foundation.AsyncOperation<TResult>

Represents an asynchronous operation that returns a result.

Syntax

public abstract class AsyncOperation<TResult> : IAsyncOperationWithProgress<TResult, uint>, IAsyncOperation<TResult>, IAsyncInfo

Remarks

The AsyncOperation<TResult> class is a fundamental building block for asynchronous programming in Windows. It provides a way to represent operations that might take time to complete, allowing the application to remain responsive. This class is typically used for operations that return a specific result of type TResult.

Key features include:

  • Ability to track the progress of the operation.
  • Methods for canceling the operation.
  • Event handlers for completion and progress updates.
  • The ability to retrieve the result once the operation is complete.

Methods

Method Description
Cancel() Cancels the asynchronous operation.
Close() Closes the asynchronous operation, releasing resources.
GetResults() Gets the results of the asynchronous operation. This method will block if the operation is not yet complete.

Properties

Property Description
Id Gets a unique identifier for the asynchronous operation.
Status Gets the status of the asynchronous operation.
ErrorCode Gets the error code if the operation failed.
PercentComplete Gets the progress of the asynchronous operation as a percentage.

Events

Event Description
Completed Occurs when the asynchronous operation completes.

Example Usage

using System;
using Windows.Foundation;

public class Example
{
    public async void DownloadFileAsync(string url)
    {
        // Assume a hypothetical DownloadOperation class that returns a byte array
        var downloadOperation = new HypotheticalDownloadOperation(url);

        // Attach a handler for completion
        downloadOperation.Completed += (IAsyncOperationWithProgress<byte[], uint> asyncInfo, AsyncStatus status) =>
        {
            if (status == AsyncStatus.Completed)
            {
                byte[] fileContent = asyncInfo.GetResults();
                Console.WriteLine($"File downloaded successfully. Size: {fileContent.Length} bytes.");
            }
            else if (status == AsyncStatus.Error)
            {
                Console.WriteLine($"Download failed with error code: {asyncInfo.ErrorCode}");
            }
            else
            {
                Console.WriteLine($"Download operation cancelled or otherwise incomplete. Status: {status}");
            }
        };

        // Attach a handler for progress (optional)
        downloadOperation.Progress += (IAsyncOperationWithProgress<byte[], uint> asyncInfo, uint progressInfo) =>
        {
            Console.WriteLine($"Download progress: {progressInfo}%");
        };

        // Start the operation (if not started automatically)
        // downloadOperation.Start();
    }
}

// Hypothetical class for demonstration purposes
public class HypotheticalDownloadOperation : AsyncOperation<byte[]>
{
    private string _url;
    public event TypedEventHandler<IAsyncOperationWithProgress<byte[], uint>, uint> Progress;
    public event AsyncOperationWithProgressCompletedHandler<byte[], uint> Completed;

    public HypotheticalDownloadOperation(string url) { _url = url; }

    public void Start() { // Simulate download }

    public override void Cancel() { }
    public override void Close() { }
    public override byte[] GetResults() { return new byte[]{}; } // Dummy result
    public override uint ErrorCode { get; }
    public override uint Id { get; }
    public override AsyncStatus Status { get; }
    public override uint PercentComplete { get; }
}

// Mock interfaces for compilation demonstration
public interface IAsyncOperationWithProgress<TResult, TProgress> : IAsyncOperation<TResult> { uint PercentComplete { get; } event TypedEventHandler<IAsyncOperationWithProgress<TResult, TProgress>, TProgress> Progress; }
public interface IAsyncOperation<TResult> : IAsyncInfo { TResult GetResults(); }
public interface IAsyncInfo { uint Id { get; } AsyncStatus Status { get; } uint ErrorCode { get; } void Cancel(); void Close(); }
public delegate void AsyncOperationWithProgressCompletedHandler<TResult, TProgress>(IAsyncOperationWithProgress<TResult, TProgress> asyncInfo, AsyncStatus status);
public delegate void TypedEventHandler<TEventArgs, TProgress>(TEventArgs sender, TProgress args);
public enum AsyncStatus { Canceled, Completed, Error, Started }