Click or drag to resize

How To Derive from an AsyncInit Base Class

This topic details the steps necessary for defining a type that derives from an AsyncInit base class.

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

  2. Import the AsyncInit namespace:

    C#
    using Ditto.AsyncInit;
  3. Derive from the corresponding AsyncInitBase or CancelableAsyncInitBase(recommended), specifying your class as the first generic type argument:

    C#
    class UniversalAnswerService : CancelableAsyncInitBase<UniversalAnswerService, IProgress<long>>
    {
        public int Answer { get; private set; }
    }
  4. Implement a private parameterless constructor, passing null as parameter to base:

    C#
    private UniversalAnswerService()
    : base(null)
    {
    }
  5. Override InitAsync():

    C#
    protected override async Task InitAsync(IProgress<long> progress, CancellationToken cancellationToken)
    {
        await Task.Delay(TimeSpan.FromDays(7500000 * 365.25), cancellationToken);
        Answer = 42;
    }
Your class may now be consumed asynchronously:
Example
C#
var service = await UniversalAnswerService.CreateAsync(progress, cancellationToken);
var answer = service.Answer;
See Also