Working with System.Threading.Tasks.Task <Stream> instead of a thread
I used a method similar to the one below in previous versions of the WCF Web API:
// grab the posted stream Stream stream = request.Content.ContentReadStream; // write it to using (FileStream fileStream = File.Create(fullFileName, (int)stream.Length)) { byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); fileStream.Write(bytesInStream, 0, bytesInStream.Length); } But in preview 6, the HttpRequestMessage.Content.ContentReadStream property disappeared. I believe that now it should look like this:
// grab the posted stream System.Threading.Tasks.Task<Stream> stream = request.Content.ReadAsStreamAsync(); But I could not understand what the rest of the code looks like inside the using statement. Can someone provide me a way to do this?
You may need to tweak this depending on what code happens before / after, and there is no error handling, but something like this:
Task task = request.Content.ReadAsStreamAsync().ContinueWith(t => { var stream = t.Result; using (FileStream fileStream = File.Create(fullFileName, (int) stream.Length)) { byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int) bytesInStream.Length); fileStream.Write(bytesInStream, 0, bytesInStream.Length); } }); If later in the code you need to make sure that this is completed, you can call task.Wait() , and it will block until it completes (or an exception is thrown).
I highly recommend Stephen Toub "Parallel Programming Patterns" to speed up the execution of some new asynchronous patterns (tasks, parallelism data, etc.) in .NET 4.
Quick and dirty fix:
// grab the posted stream Task<Stream> streamTask = request.Content.ReadAsStreamAsync(); Stream stream = streamTask.Result; //blocks until Task is completed Keep in mind that the fact that the sync version has been removed from the API suggests that you really should try to learn new asynchronous programming paradigms to avoid overflowing many threads under heavy load.
You could, for example:
streamTask.ContinueWith( _ => { var stream = streamTask.Result; //result already available, so no blocking //work with stream here } ) or with new async wait functions:
//async wait until task is complete var stream = await request.Content.ReadAsStreamAsync(); Take time to find out async / wait. It is very comfortable.
Here's how you can do it better with async and await :
private async void WhatEverMethod() { var stream = await response.Content.ReadAsStreamAsync(); using (FileStream fileStream = File.Create(fullFileName, (int)stream.Length)) { byte[] bytesInStream = new byte[stream.Length]; stream.Read(bytesInStream, 0, (int)bytesInStream.Length); fileStream.Write(bytesInStream, 0, bytesInStream.Length); } });