使用 System.Threading.Tasks.Task而不是流

发布于 2024-12-19 13:25:10 字数 707 浏览 0 评论 0原文

我在以前版本的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

灯角 2024-12-26 13:25:10

您可能必须根据之前/之后发生的代码进行调整,并且没有错误处理,但类似这样:

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 的并行编程模式来了解.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:

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);
    }
});

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.

与他有关 2024-12-26 13:25:10

快速而肮脏的修复:

// grab the posted stream
Task<Stream> streamTask = request.Content.ReadAsStreamAsync();
Stream stream = streamTask.Result; //blocks until Task is completed

请注意,同步版本已从 API 中删除这一事实表明您确实应该尝试学习新的异步范例,以避免在高负载下吞噬许多线程。

例如,您可以:

streamTask.ContinueWith( _ => {
    var stream = streamTask.Result; //result already available, so no blocking
    //work with stream here
} )

或使用新的异步等待功能:

//async wait until task is complete
var stream = await request.Content.ReadAsStreamAsync(); 

花时间学习异步/等待。这非常方便。

Quick and dirty fix:

// grab the posted stream
Task<Stream> streamTask = request.Content.ReadAsStreamAsync();
Stream stream = streamTask.Result; //blocks until Task is completed

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:

streamTask.ContinueWith( _ => {
    var stream = streamTask.Result; //result already available, so no blocking
    //work with stream here
} )

or with new async await features:

//async wait until task is complete
var stream = await request.Content.ReadAsStreamAsync(); 

Take time to learn async/await. It's pretty handy.

流星番茄 2024-12-26 13:25:10

以下是如何使用 asyncawait 更好地做到这一点:

    private async void WhatEverMethod()
    {
        var stream = await response.Content.ReadAsStreamAsync();

        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);
        }
    });

Here is how you can do this better with async and await:

    private async void WhatEverMethod()
    {
        var stream = await response.Content.ReadAsStreamAsync();

        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);
        }
    });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文