我在以前版本的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,(int)bytesInStream.Length); fileStream.Write(bytesInStream,bytesInStream.Length); }
但是在预览6中,HttpRequestMessage.Content.ContentReadStream属性消失了.我相信它现在应该像这样:
// grab the posted stream System.Threading.Tasks.Task<Stream> stream = request.Content.ReadAsStreamAsync();
解决方法
您可能必须根据之前/之后发生的代码进行调整,并且没有错误处理,但是这样的事情:
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,(int) bytesInStream.Length); fileStream.Write(bytesInStream,bytesInStream.Length); } });
如果在代码中稍后需要确保已完成此操作,则可以调用task.Wait()并将其阻塞,直到完成(或抛出异常).
我强烈推荐Stephen Toub的Patterns of Parallel Programming来加速.NET 4中的一些新的异步模式(任务,数据并行等).