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();Best practices
Section titled “Best practices”- Name the method with
Asyncsuffix. - Avoid using
.Resultor.Wait()on the returned task.
Real-world usage example
Section titled “Real-world usage example”API calls: HttpClient.GetStringAsync returns Task<string>. JsonSerializer.DeserializeAsync returns Task<T>.
Example: HttpClient documentation