我在以前版本的 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()
并且它将阻塞直到完成(或抛出异常)。
我强烈推荐斯蒂芬·托布的并行编程的模式 http://www.microsoft.com/download/en/details.aspx?id=19222快速了解 .NET 4 中的一些新的异步模式(任务、数据并行性等)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)