I have the following code:
// Get all of the files from the local storage directory.
var files = await folder.GetFilesAsync();
// Map each file to a stream corresponding to that file.
var streams = files.Select(async f => { return await f.OpenStreamForWriteAsync(); });
I would expect streams
to be of type IEnumerable<Stream>
but in fact it is of IEnumberable<Task<Stream>>
, which is what I would've expected had I omitted the await keyword. The return type of OpenStreamForWriteAsync
is Task<Stream>
— surely awaiting it should produce a Stream
?
So, why is the return await statement returning a Task?
Thanks for your help.
All async
methods return either void
, Task
, or Task<TResult>
. The lambda is just an anonymous method, and thus that still applies. It's essentially the same as this named method:
private static async Task<Stream> Foo(TypeGOesHere f )
{
return await f.OpenStreamForWriteAsync();
}
In order to make it return a Stream
it would need to be a blocking method, rather than an async method:
private static Stream Foo(TypeGOesHere f )
{
return f.OpenStreamForWriteAsync().Result;
}
You probably don't want that.
You can turn your IEnumerable<Task<Stream>>
into a Task<Stream[]>
by using Task.WhenAll
if that helps you:
Task<Stream[]> resultTask = Task.WhenAll(streams);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With