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

前端 未结 3 809
挽巷
挽巷 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:35

    Quick and dirty fix:

    // grab the posted stream
    Task 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.

提交回复
热议问题