Task Returning a value
suggest changeA 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");
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents