tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

New Task.WaitAsync method in .NET 6

21 Jan 2022 1 mins Multithreading/Parallelism/Asynchronous/Concurrency

.NET 6 has this new handy method on Task called WaitAsync. It might not look like a big deal. Basically, the asynchronous version of Wait, right? Yes, but also it closes one gap that was often implemented poorly.

Sometimes you have task method that does not support any kind of cancellation, yet you still want to use it. The often-used approach is to use Task.Delay and plug it into Task.WhenAny. I created my own version quite some time ago here. The catch is to properly cancel the Task.Delay task in case the original task completed before timeout. Else the timer queue might become bottleneck.

However, starting with .NET 6 you can use the mentioned WaitAsync method to do the same.

await Foo().WaitAsync(TimeSpan.FromSeconds(5));

async Task Foo()
{
	while (true)
	{
		await Task.Delay(100);
	}
}

Easy and direct. No extra code needed. The WaitAsync has other overloads where you can also pass CancellationToken giving you more options.

Although libraries providing task-based methods should have story for passing CancellationTokens, it is not always the case. It’s nice to have option for “timeout” now directly in .NET.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He's focused on data and business layers, language constructs, parallelism, databases and performance. He's Microsoft Most Valuable Professional and frequent speaker. You can read his articles, guides and tips and tricks at www.tabsoverspaces.com.