Task Returning a value

suggest change

A task that returns a value has the type Task<TResult>, where TResult is the type of that value. Read the outcome from the Result property. Reading Result blocks until the task finishes, and it throws if the task faulted.

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

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

        return sum;
    });

Console.WriteLine(t.Result); // Output: 124750

If the task is asynchronous, await unwraps its result. DownloadStringTaskAsync was added in .NET Framework 4.5.

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents