2235.md

February 3, 2022 ยท View on GitHub

Using the new C# 5.0 keywords results in code that can still be read sequentially and also improves maintainability a lot, even if you need to chain multiple asynchronous operations. For example, rather than defining your method like this:

public Task<Data> GetDataAsync()
{
	return MyWebService.FetchDataAsync()
		.ContinueWith(t => new Data(t.Result));
}

define it like this:

public async Task<Data> GetDataAsync()
{
	string result = await MyWebService.FetchDataAsync();
	return new Data(result);
}

Tip: Even if you need to target .NET Framework 4.0 you can use the async and await keywords. Simply install the Async Targeting Pack.