加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用System.Threading.Tasks.Task而不是Stream

发布时间:2020-12-15 17:49:30 所属栏目:百科 来源:网络整理
导读:我在以前版本的WCF Web API上使用了类似下面的方法: // grab the posted streamStream stream = request.Content.ContentReadStream;// write it to using (FileStream fileStream = File.Create(fullFileName,(int)stream.Length)) { byte[] bytesInStream
我在以前版本的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();

但我无法弄清楚在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,(int) bytesInStream.Length);
        fileStream.Write(bytesInStream,bytesInStream.Length);
    }
});

如果在代码中稍后需要确保已完成此操作,则可以调用task.Wait()并将其阻塞,直到完成(或抛出异常).

我强烈推荐Stephen Toub的Patterns of Parallel Programming来加速.NET 4中的一些新的异步模式(任务,数据并行等).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读