tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Using await using (IAsyncDisposable) with ConfigureAwait

24 Apr 2019 2 mins .NET Core, C#, Multithreading/Parallelism/Asynchronous/Concurrency

C# 8 is bringing asynchronous disposables via new IAsyncDisposable and although the basic concept is easy to grasp, other rules of awaiting still apply here. And one of these is the usage of ConfigureAwait call.

Let’s take this simple class.

class AwaitUsingConfigureAwaitTest: IAsyncDisposable
{
	public async ValueTask DisposeAsync()
	{
		await Task.CompletedTask;
	}

	public void Dummy() { }
}

The DisposeAsync is just dummy, you don’t have to think about it here.

The ConfigureAwait extension method exists for IAsyncDisposable, thus it can be called inside the await using.

async Task FooBar()
{
	await using (var test = new AwaitUsingConfigureAwaitTest().ConfigureAwait(false))
	{
		test.Dummy();
	}
}

But doing it like this results in error CS1061: 'ConfiguredAsyncDisposable' does not contain a definition for 'Dummy' and no accessible extension method 'Dummy' accepting a first argument of type 'ConfiguredAsyncDisposable' could be found (are you missing a using directive or an assembly reference?). Bummer. Yet we can find our way out… Simply by using an extra variable.

async Task FooBar()
{
	var test = new AwaitUsingConfigureAwaitTest();
	await using (test.ConfigureAwait(false))
	{
		test.Dummy();
	}
}

Not as succinct as I’d like (not that ConfigureAwait is smooth either). But all is not lost. At the time of writing, the C# 8 isn’t final yet, so at the end compiler might do some magic for us.

By the way, support in ConfigureAwaitChecker is already planned, if you’d like to ask.

Related post.

Profile Picture Jiří Činčura is .NET, C# and Firebird expert. He focuses on data and business layers, language constructs, parallelism, databases and performance. For almost two decades he contributes to open-source, i.e. FirebirdClient. He works as a senior software engineer for Microsoft. Frequent speaker and blogger at www.tabsoverspaces.com.