Sometimes, I want to do something with the result of an async method, for example:
var foos = (await GetObjectAsync<IEnumerable<Foo>>()).ToList();
But this notation can be hardly readable because of the parenthesis. If I call another asynchronous method with the result, multiple await expressions are nested, for example:
var result = (await (await GetObjectAsync<IEnumerable<Foo>>()).First().SomeMethodAsync()).GetResult();
I would like to write a more fluent equivalent like:
var foos = GetObjectAsync<IEnumerable<Foo>>()
.Async()
.First()
.SomeMethodAsync()
.Async()
.GetResult();
I read the documentation but the only thing that have the right signature (unless I missed something) is Result, and Result is not what I want because it is not an equivalent of await.
Does such a method exist? Can I create an extension to do this if it does not exist?
awaitturns your code into a state machine behind the scenes, it should not go unnoticedTask<T>and returns aTthat would behave the same as awaiting it. The only possible implementation of such a method is to either not return the actual result, or to synchronously block (unless the task was completed before you called such a method).whereis a keyword, and there is a functional equivalent (Where), so it doesn't seem an unreasonable question.awaitinterrupts (most of the time) the current method execution and waits for a "callback" to continue where it left later, therefore a synchronous method equivalent cannot exist. You can chain the continuation and map theToListon completion but this will return still a Task<T>, not T and then you will have to await on the T or block. ToList is an extension on IEnumerable<T> and not on Task<IEnumerable<T>> so you will need either something like Async(result => result.ToList()) which returns a Task<List<T>> or a blocking call to chain it.