使用 System.Threading.Tasks.Task而不是流
我在以前版本的 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 语句中的其余代码应该是什么样子。谁能给我提供一种方法吗?
I was using a method like below on the previous versions of 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 on the preview 6, HttpRequestMessage.Content.ContentReadStream
property is gone. I believe that it now should look like this one:
// grab the posted stream
System.Threading.Tasks.Task<Stream> stream = request.Content.ReadAsStreamAsync();
But I couldn't figure out what the rest of the code should be like inside the using statement. Can anyone provide me a way of doing it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能必须根据之前/之后发生的代码进行调整,并且没有错误处理,但类似这样:
如果稍后在代码中,您需要确保此操作已完成,则可以调用
task .Wait()
并且它将阻塞,直到完成(或抛出异常)。我强烈推荐 Stephen Toub 的并行编程模式来了解.NET 4 中一些新的异步模式(任务、数据并行性等)的速度。
You might have to adjust this depending on what code is happening before/after, and there's no error handling, but something like this:
If, later in your code, you need to ensure that this has completed, you can call
task.Wait()
and it will block until this has completed (or thrown an exception).I highly recommend Stephen Toub's Patterns of Parallel Programming to get up to speed on some of the new async patterns (tasks, data parallelism etc) in .NET 4.
快速而肮脏的修复:
请注意,同步版本已从 API 中删除这一事实表明您确实应该尝试学习新的异步范例,以避免在高负载下吞噬许多线程。
例如,您可以:
或使用新的异步等待功能:
花时间学习异步/等待。这非常方便。
Quick and dirty fix:
Be aware that the fact that the sync version has been removed from the API suggests that you should really be attempting to learn the new async paradigms to avoid gobbling up many threads under high load.
You could for instance:
or with new async await features:
Take time to learn async/await. It's pretty handy.
以下是如何使用
async
和await
更好地做到这一点:Here is how you can do this better with
async
andawait
: