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.
Determine the types of the initialization arguments (if any), e.g. IProgress<long>.
Import the AsyncInit namespace:
using Ditto.AsyncInit;
Implement the corresponding IAsyncInit or ICancelableAsyncInit(recommended):
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; } }
Implement a private parameterless constructor:
private UniversalAnswerService()
{
}
Implement a CreateAsync() method:
public async Task<UniversalAnswerService> CreateAsync(IProgress<long> progress, CancellationToken cancellationToken) { return AsyncActivator.CreateAsync<UniversalAnswerService, IProgress<long>>(progress, cancellationToken); }
var service = await UniversalAnswerService.CreateAsync(progress, cancellationToken); var answer = service.Answer;