The APM, Anonymous Methods and Lambda Expressions
In this post I would like to continue from where I left of in my previous post about the Asynchronous Programming Model, and show how the APM could be more concise using Anonymous Methods and Lambda Expressions.
Using "classic" delegates the code to implement the APM looks like this (as shown in greater details in my previous post):
public void ClassicAsync(int num)
{
DateTime start = DateTime.Now;
Console.WriteLine("Starting async calculation at: {0}", start);
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
del.BeginInvoke(num, CalcCompleted, start);
}
private void CalcCompleted(IAsyncResult result)
{
DateTime start = (DateTime)result.AsyncState;
Func<int, int> del = (Func<int, int>)((AsyncResult)result).AsyncDelegate;
int prime = del.EndInvoke(result);
DateTime end = DateTime.Now;
TimeSpan length = end.Subtract(start);
Console.WriteLine("Completed async calculation at: {0}", end);
Console.WriteLine("Async calculation took {0:F} seconds.", length.TotalSeconds);
}
With an anonymous method we can write the callback method inline like this:
public void AnonymousAsync(int num)
{
DateTime start = DateTime.Now;
Console.WriteLine("Starting anonymous async calculation at: {0}", start);
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
del.BeginInvoke(num, delegate(IAsyncResult result)
{
int prime = del.EndInvoke(result);
Console.WriteLine(prime);
DateTime end = DateTime.Now;
TimeSpan length = end.Subtract(start);
Console.WriteLine("Completed anonymous async calculation at: {0}", end);
Console.WriteLine("Async calculation took {0:F} seconds.", length.TotalSeconds);
}, null);
}
And, finally, using a lambda expression the implementation is even more concise:
public void LambdaAsync(int num)
{
DateTime start = DateTime.Now;
Console.WriteLine("Starting lambda async calculation at: {0}", start);
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
del.BeginInvoke(num, result =>
{
int prime = del.EndInvoke(result);
Console.WriteLine(prime);
DateTime end = DateTime.Now;
TimeSpan length = end.Subtract(start);
Console.WriteLine("Completed lambda async calculation at: {0}", end);
Console.WriteLine("Async calculation took {0:F} seconds.", length.TotalSeconds);
}, null);
}
0 comments:
Post a Comment