How can I convert this method to async

前端 未结 2 1213
刺人心
刺人心 2021-01-17 06:58

I have a simple method shown below. How can I convert it to async?

public string Smethod0(HttpWebRequest httpWebRequest0)
{
    return new StreamReader(Smet         


        
相关标签:
2条回答
  • 2021-01-17 07:53

    It always depends on the method, but in this case, you already have a good way to return an async result, without even making the method itself async:

    public Task<string> Smethod0(HttpWebRequest httpWebRequest0)
    {
        return new StreamReader(Smethod_1(httpWebRequest0).GetResponseStream(),
            Encoding.UTF8, true).ReadToEndAsync();
    }
    

    It would be pointless to add async and await to the method, because the method itself has no need to actually await anything. Doing that would just add an extra layer of awaiting for no useful purpose.

    If you want to be technically more correct, you should also dispose your reader. You could improve your original implementation like this:

    public async Task<string> Smethod0(HttpWebRequest httpWebRequest0)
    {
        using (StreamReader reader = new StreamReader(
            Smethod_1(httpWebRequest0).GetResponseStream(), Encoding.UTF8, true))
        {
            return await reader.ReadToEndAsync();
        }
    }
    

    Note that in this case, there is a point to awaiting the result, because you don't want to dispose the reader until you're done.

    0 讨论(0)
  • 2021-01-17 07:55

    You can make it async by using async/await mechanism:

    public async Task<string> Smethod0(HttpWebRequest httpWebRequest0)
        {
            return await new StreamReader(Smethod_1(httpWebRequest0).GetResponseStream(),
            Encoding.UTF8, true).ReadToEndAsync();
        }
    

    Also see I'm using ReadToEndAsync() in stead of ReadToEnd().

    And Steve is right, you'll have to dispose the stream first before returning the result.

    0 讨论(0)
提交回复
热议问题