A Microsoft docs tutorial introduced me to this code:
var repositories = await JsonSerializer.DeserializeAsync<List<Repository>>(await streamTask);
I am familiar with async
and await
and how to use them, or so I thought. The tutorial mentions that this is an example of using an “await expression” - that’s fine, after all, the expression doesn’t look all that odd on it’s own, but I have yet to find another, single example of any C# code like this - where an await expression is being passed to a method - anywhere. The await keyword here almost looks like it’s functioning as a parameter modifier e.g. ref, out, in.
So my question is, is this a new feature, is it just rarely used, or is it just new to me? It’s functionality seems obvious, intuitive, and useful, but like I mentioned, I have yet to find another example of similar code anywhere. Can someone please explain this, or downvote me and give me a sanity check, please?
Tutorial I was looking through:
https://docs.microsoft.com/en-us/dotnet/csharp/tutorials/console-webapiclient
Note - I will format this as a more direct question if needed, but as of now I am intentionally framing this in an open manner.
CodePudding user response:
I have yet to find another, single example of any C# code like this - where an await expression is being passed to a method - anywhere.
It's not uncommon. As another commenter noted, await
keywords are often split into separate lines for debuggability or readability reasons. But I've seen this kind of usage many times.
Another somewhat common pattern for await
expressions is to use parentheses to extract part of a result:
var x = (await SomethingAsync()).Property;
The await keyword here almost looks like it’s functioning as a parameter modifier e.g. ref, out, in.
I assume it only looks that way because it's not familiar and colored like a keyword in your editor. await
- like new
- is a keyword that exists in an expression.
So my question is, is this a new feature, is it just rarely used, or is it just new to me?
New to you.
In the original async
CTP, await
expressions didn't work correctly and had to be split into separate statements. But that limitation was removed before the official async
support was released, so await
expressions have been supported since day 1 (ignoring prereleases).