There's some code I can't change:
protected virtual void Method1() { }
private void Method2() { /* ... */ }
public void Method3()
{
Method1();
Method2();
}
And when Method3() is called, I have to call a method returning a Task in the override of Method1. However, after that call, I need to know if Method2 has been called yet.
protected override async void Method1()
{
await MyOtherMethodAsync();
bool method2HasBeenCalledYet = ??
if (method2HasBeenCalledYet)
{
// ...
}
else
{
// ...
}
}
The thing is, it depends on whether MyOtherMethodAsync is actually asynchronous (like with a Task.Run()) or not (with, for example, a Task.CompletedTask).
I had an idea, it works every time I tested it, but I don't know if there are cases when it wouldn't work (edit: there are) or if there are more elegant solutions (edit: there clearly are).
protected override async void Method1()
{
bool method2HasBeenCalledYet = await IsAsync(MyOtherMethodAsync);
if (method2HasBeenCalledYet)
{
// ...
}
else
{
// ...
}
}
private async Task<bool> IsAsync(Func<Task> asyncAction)
{
int beforeThreadId = Thread.CurrentThread.ManagedThreadId;
await asyncAction().ConfigureAwait(false);
int afterThreadId = Thread.CurrentThread.ManagedThreadId;
return beforeThreadId != afterThreadId;
}
--
Edit with the solution given by @Crowcoder and @Servy:
protected override async void Method1()
{
var task = MyOtherMethodAsync();
if (!task.IsCompleted)
{
await task;
// ...
}
else
{
// ...
}
}
IsCompletedandStatuswhich you might make use of.