c# - 使用 System.Threading.Tasks.Task<Stream> 而不是 Stream

标签 c# asynchronous wcf-web-api

我在以前版本的 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/

相关文章:

c# - 对用 years 填充 ComboBox 感到困惑

javascript - 在MVC中打开一个新的窗口表单操作方法

c# - 使用在多个列上具有主键的 Entity Framework 更新数据库

wcf - 使用 WCF WebApi 的异步 REST 服务

asp.net-mvc-3 - Wcf Web Api 服务路由与常规 asp.net mvc 路由冲突(Web api 预览版 4)

c# - onClick 和 onClientClick 事件一起使用。不适用于 Internet Explorer

javascript - gjs 如何使用 g_data_input_stream_read_line_async 在 Gnome Shell 扩展中读取套接字流

asynchronous - Rust 异步程序中的性能和内存问题

c# - 此 MSDN 示例中 Lazy<T> 的用途

.net - 有没有办法使用 WCF Web API 控制 JSON 格式?