I have been wondering…
Do the new Async constructs actually allow for intermediate results without writing new code on the consumer side?
Let me elaborate with an example.
Let’s say we have a method that downloads data into a byte array or a stream, whichever is better.
Is it possible, that a method that awaits said method can start consuming the byte array or stream before the download is complete with the built in async features? What I could do is raise events everytime a certain part of the stream is downloaded, but that increases clutter again.
Let me write a code example (from the top of my head, will not be correct code!) that I (would) expect to result in intermediate results, given the awaited method returns such results.
io.Stream data = await downloadData();
byte[4096] buffer = new byte[4096];
while (!data.EOF) {
(await?) data.Read(buffer, offset, 4096);
}
As of now, Stream.Read is not awaitable, do we have any method of doing this, though? I want to be able to await through a transfer. Am I overseeing anything?
If you’re using
Streamin .Net 4.5, you can use itsReadAsync()method for this:If you mean that your stream does not have a method such as
ReadAsync(), but does support asynchrony using theBeginXxx(),EndXxx()pattern, and you want to useawait, then you can do that too:But, if you only have a synchronous
Read()method, the only way to use it withasyncwould be to start a newTaskon a background thread:The problem with this code is that it still blocks a thread, which is what
asyncis trying to avoid. But it might still be useful if the method runs on a GUI thread, and you can’t run the whole loop on a background thread.