我在以前版本的 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);
}
但是在预览版 6 中,HttpRequestMessage.Content.ContentReadStream
属性消失了。我相信它现在应该看起来像这样:
// grab the posted stream
System.Threading.Tasks.Task<Stream> stream = request.Content.ReadAsStreamAsync();
但我无法弄清楚 using 语句中的其余代码应该是什么样的。任何人都可以提供一种方法吗?
最佳答案
您可能需要根据之前/之后发生的代码进行调整,并且没有错误处理,但像这样:
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);
}
});
如果稍后在您的代码中需要确保此操作已完成,您可以调用 task.Wait()
它将阻塞直到此操作已完成(或抛出异常)。
我强烈推荐 Stephen Toub 的 Patterns of Parallel Programming加快了解 .NET 4 中的一些新异步模式(任务、数据并行性等)。
关于c# - 使用 System.Threading.Tasks.Task<Stream> 而不是 Stream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8399994/