I have a simple method shown below. How can I convert it to async?
public string Smethod0(HttpWebRequest httpWebRequest0)
{
return new StreamReader(Smet
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.
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.