Click or drag to resize

How To Implement an AsyncInit Interface

This topic details the steps necessary for defining a type that implements an AsyncInit interface.

In some cases, a type cannot be derived from a particular AsyncInitBase or CancelableAsyncInitBase, e.g. when it must derive from a predefined base class. In such scenarios IAsyncInit and ICancelableAsyncInit should be used instead.

  1. Determine the types of the initialization arguments (if any), e.g. IProgress<long>.

  2. Import the AsyncInit namespace:

    C#
    using Ditto.AsyncInit;
  3. Implement the corresponding IAsyncInit or ICancelableAsyncInit(recommended):

    C#
    class UniversalAnswerService : ICancelableAsyncInit<IProgress<long>>
    {
        public int Answer { get; private set; }
    
        async Task ICancelableAsyncInit<IProgress<long>>.InitAsync(IProgress<long> progress, CancellationToken cancellationToken)
        {
            await Task.Delay(TimeSpan.FromDays(7500000 * 365.25), cancellationToken);
            Answer = 42;
        }
    }
  4. Implement a private parameterless constructor:

    C#
    private UniversalAnswerService()
    {
    }
  5. Implement a CreateAsync() method:

    C#
    public async Task<UniversalAnswerService> CreateAsync(IProgress<long> progress, CancellationToken cancellationToken)
    {
        return AsyncActivator.CreateAsync<UniversalAnswerService, IProgress<long>>(progress, cancellationToken);
    }
Your class may now be consumed asynchronously:
Example
C#
var service = await UniversalAnswerService.CreateAsync(progress, cancellationToken);
var answer = service.Answer;
See Also