.NET Framework Task: Returning a value


Example

Task that return a value has return type of Task< TResult > where TResult is the type of value that needs to be returned. You can query the outcome of a Task by its Result property.

Task<int> t = Task.Run(() => 
    {
        int sum = 0;

        for(int i = 0; i < 500; i++)
            sum += i;

        return sum;
    });

Console.WriteLine(t.Result); // Outuput 124750

If the Task execute asynchronously than awaiting the Task returns it's result.

public async Task DoSomeWork()
{
    WebClient client = new WebClient();
    // Because the task is awaited, result of the task is assigned to response
    string response = await client.DownloadStringTaskAsync("http://somedomain.com");
}