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

前端 未结 3 822
挽巷
挽巷 2021-02-15 15:27

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 i         


        
3条回答
  •  渐次进展
    2021-02-15 15:32

    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.

提交回复
热议问题