text
stringlengths
0
13.4k
{
foreach(var inner in ex.InnerExceptions)
Console.WriteLine("Task failed: " + inner.Message);
GoalKicker.com – .NET Framework Notes for Professionals
130
}
Section 42.3: Task: Returning a value
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");
}
Section 42.4: Parallel.ForEach
This example uses Parallel.ForEach to calculate the sum of the numbers between 1 and 10000 by using multiple
threads. To achieve thread-safety, Interlocked.Add is used to sum the numbers.
using System.Threading;
int Foo()
{
int total = 0;
var numbers = Enumerable.Range(1, 10000).ToList();
Parallel.ForEach(numbers,
() => 0, // initial value,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // total = 50005000
}
Section 42.5: Parallel.For
This example uses Parallel.For to calculate the sum of the numbers between 1 and 10000 by using multiple
threads. To achieve thread-safety, Interlocked.Add is used to sum the numbers.
using System.Threading;
int Foo()
{
int total = 0;
Parallel.For(1, 10001,
GoalKicker.com – .NET Framework Notes for Professionals
131
() => 0, // initial value,
(num, state, localSum) => num + localSum,
localSum => Interlocked.Add(ref total, localSum));
return total; // total = 50005000
}
Section 42.6: Task: basic instantiation and Wait
A task can be created by directly instantiating the Task class...
var task = new Task(() =>
{
Console.WriteLine("Task code starting...");
Thread.Sleep(2000);
Console.WriteLine("...task code ending!");
});
Console.WriteLine("Starting task...");
task.Start();
task.Wait();
Console.WriteLine("Task completed!");
...or by using the static Task.Run method:
Console.WriteLine("Starting task...");