In C# when an Task
or Task<T>
method is returned from within a using
statement is there any risk of the cleanup not properly occurring, or is this a poor practice? What concerns are there as it pertains to the closure of the variable in the using
block?
Consider the following:
public Task<string> GetAsync(string url)
{
using (var client = new HttpClient())
{
return client.GetStringAsync(url);
}
}
In the example above the asynchronous operation is represented by the client.GetStringAsync(url)
, I'm simply returning that Task<string>
for the consumer to await
. What happens to the client
as it is in a using
- does it get cleaned up before it is awaited or garbage collected, or does it cause other issues?
Would it be better to use async
and await
in the cause of using
statements like this, if so why?
public async Task<string> GetAsync(string url)
{
string response = string.Empty;
using (var client = new HttpClient())
{
response = await client.GetStringAsync(url);
}
return response;
}
Or
public async Task<string> GetAsync(string url)
{
using (var client = new HttpClient())
{
return await client.GetStringAsync(url);
}
}
What is the difference?