Working with System.Threading.Tasks.Task<Stream> instead of Stream

删除回忆录丶 提交于 2019-12-03 13:21:47

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.

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.

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);
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!