15.02.2015 Views

C# 4 and .NET 4

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

synchronization ❘ 529<br />

for (int i = 0; i < taskCount; i++)<br />

{<br />

Console.WriteLine("task for {0}, result: {1}", i, calcs[i].Result);<br />

}<br />

code snippet EventSample/Program.cs<br />

barrier<br />

For synchronization, .<strong>NET</strong> 4 offers the new Barrier class. Barrier is great for a scenario where work is<br />

forked into multiple tasks, <strong>and</strong> the work needs to be joined afterward. Barrier is used for participants need<br />

to be synchronized. While the job is active, additional participants can be added dynamically, for example,<br />

child tasks that are created from a parent task. Participants can wait until the work is done by all the other<br />

participants before continuing.<br />

The sample application uses a collection containing 2,000,000 strings. Multiple tasks are used to iterate<br />

through the collection <strong>and</strong> count the number of strings starting with a, b, c, <strong>and</strong> so on.<br />

The method FillData() creates a collection <strong>and</strong> fills it with r<strong>and</strong>om strings.<br />

public static IEnumerable FillData(int size)<br />

{<br />

List data = new List(size);<br />

R<strong>and</strong>om r = new R<strong>and</strong>om();<br />

for (int i = 0; i < size; i++)<br />

{<br />

data.Add(GetString(r));<br />

}<br />

return data;<br />

}<br />

private static string GetString(R<strong>and</strong>om r)<br />

{<br />

StringBuilder sb = new StringBuilder(6);<br />

for (int i = 0; i < 6; i++)<br />

{<br />

sb.Append((char)(r.Next(26) + 97));<br />

}<br />

return sb.ToString();<br />

}<br />

code snippet BarrierSample/Program.cs<br />

The CalculationInTask() method defines the job that’s done by a task. With the parameter, a tuple<br />

containing four items is received. The third parameter is a reference to the Barrier instance. When the job<br />

is done by the task, the task removes itself from the barrier with the RemoveParticipant() method.<br />

static int[] CalculationInTask(object p)<br />

{<br />

var p1 = p as Tuple;<br />

Barrier barrier = p1.Item3;<br />

List data = p1.Item4;<br />

int start = p1.Item1 * p1.Item2;<br />

int end = start + p1.Item2;<br />

Console.WriteLine("Task {0}: partition from {1} to {2}",<br />

Task.Current.Id, start, end);<br />

int[] charCount = new int[26];<br />

for (int j = start; j < end; j++)<br />

{<br />

char c = data[j][0];<br />

charCount[c - 97]++;<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!