# Asynchronously wait for a task to complete and do some async action while waiting

I have a long-running task. My goal is to create a method that will allow me to:

1. Asynchronously wait for this task to complete
2. While waiting on a task, do some async action once in a while. This 'action' basically tells some remote service that task is not dead and still executing.

I've written the following code to solve this problem. Please have a look and share your thoughts!

public delegate Task AsyncAction();

{
{
var timeoutCancellationTokenSource = new CancellationTokenSource();

{
timeoutCancellationTokenSource.Cancel();
return true;
}
else
{
return false;
}
}

{
while (true)
{
if (completed)
{
break;
}

await onTimeout().ConfigureAwait(false);
}

}
}


Usage:

var task = Task.Delay(TimeSpan.FromSeconds(15));

{
Console.WriteLine("Waiting...");
})
.Wait();

• In TimeoutAfter() you can remove the else and just return false. – Heslacher Nov 26 '14 at 9:59
• Why do you await the task again after it completed in the WhenAny? – Dave Van den Eynde Jun 20 '17 at 12:12
• And why do you care to cancel that delay task you have no intention of awaiting again? – Dave Van den Eynde Jun 20 '17 at 12:12

public delegate Task AsyncAction();


Instead of creating a custom delegate type, you could just reuse Func<Task> (even though logically, it is an action and not a function).

return Task.FromResult(true);


Consider adding an overload that takes a non-async onTimeout delegate, so that this confusing code wasn't required.

Or, if you do something like this often, have some TaskEx.Completed, or something like that.

Otherwise, good job. I especially like that you remembered to use ConfigureAwait(false) everywhere.