Skip to content

Task<T> for returning value

Context: When an async method needs to return a value, use Task<T>. The await expression yields the value of type T.

using System.Data.SqlClient;
using System.Threading.Tasks;
using Dapper;
public class UserRepository
{
private string connectionString = "Server=.;Database=MyDb;Trusted_Connection=true;";
public async Task<int> GetUserCountAsync()
{
using var connection = new SqlConnection(connectionString);
return await connection.QueryFirstAsync<int>("SELECT COUNT(*) FROM Users");
}
}
// Usage
// int count = await new UserRepository().GetUserCountAsync();
  • Name the method with Async suffix.
  • Avoid using .Result or .Wait() on the returned task.

API calls: HttpClient.GetStringAsync returns Task<string>. JsonSerializer.DeserializeAsync returns Task<T>.

Example: HttpClient documentation