Topics:
Higher Calling Functions
Lazy Code
Asynch and Parallel
static void Main(string[] args)
{
var elapsed = Measure(() =>
{
var numbers = new[]{3, 5, 7, 9, 11, 13};
foreach(var prime in numbers.Find(IsPrime).Take(2))
{
Console.WriteLine(prime);
}
});
Console.WriteLine(elapsed);
//Parallel
Parallel.Invoke(new Action[]
{
() => FindLargePrimes(3,100),
() => FindLargePrimes(101,200)
});
//Task
var task = new Task<IEnumerable<int>>(
() => FindLargePrimes(3,100)
);
var task2 = task.ContinueWith((antecedent) =>
{
foreach(var number in antecedent.Result)
{
Console.WriteLine(number);
}
});
task.Start();
Console.WriteLine("Doing other work");
task2.Wait();
}
private static IEnumerable<int> Find(this IEnumerable<int> values, Func<int, bool> test)
{
foreach(var number in values)
{
if(test(number))
{
yield return number;
}
}
}
private static bool IsPrime(int number) [...]
private TimeSpan Measure(Action action)
{
var watch = new StopWatch();
watch.start();
action();
return watch.Elapsed;
}
Reference: Scott Allen's C# Fundamentals - Part 2
No comments:
Post a Comment