I have the following method from an API which I have no control over.
public void Start(Action OnReady);
In general I am fine with callbacks but sometimes you have callback that triggers a callback and so on. Therefore I would like to wrap it into a async method and maybe also include the possibility to cancel the action. Something like this:
await Start(cancellationToken);
This is what I came up with:
public Task Start(CancellationToken cancellationToken)
{
return Task.Run(() =>
{
cancellationToken.ThrowIfCancellationRequested();
var readyWait = new AutoResetEvent(false);
cancellationToken.Register(() => readyWait?.Set());
Start(() => { readyWait.Set(); }); //this is the API method
readyWait.WaitOne();
readyWait.Dispose();
readyWait = null;
if(cancellationToken.IsCancellationRequested)
{
APIAbort(); //stop the API Start method from continuing
cancellationToken.ThrowIfCancellationRequested();
}
}, cancellationToken);
}
I think there is room for improvement but one thing that comes to my mind is what does this method in this context?
readyWait.WaitOne();
I wanted to write an async method to not block any thread, but that's exactly what WaitOne does. Of course it does not block the calling thread because of the task, but does the task gets its own thread? I would be fine if only the task would be blocked, but I don't want to block a thread that might be in use somewhere else.