Music Video Without Cameras

The thoughts of a mere mortal programmer

I just saw the first Microsoft Windows ad featuring Bill Gates and Jerry Seinfeld. This ad campaign is Microsoft's answer to Apple's Mac vs. PC ads which have been going unchallenged for over two years.
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);
}
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);
}
public void LambdaAsync(int num)Read more...
{
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);
}
In my previous post I described how delegates have evolved over the various versions of the .NET framework. In this post I want to elaborate and describe how to use delegates to implement asynchronous programming.
Many of today's PCs have multiple processors/cores in them, and there's a definite trend among processor makers to gradually increase that number in future models. In order to utilize the increasing number of cores, computer programs need to parallelize their execution, and assign processor intensive tasks to dedicated threads. Writing robust multi-threaded software is not easy. Threads need to be synchronized, data locked, and dead-locks are difficult to avoid. This increases the challenge for developers who need to write robust and efficient multi-threaded code.
To help programmers out, Microsoft introduced the Asynchronous Programming Model which simplifies multi-threaded programming. They have implemented it themselves in many classes throughout the .NET framework such as the FileStream, Socket, WebRequest, SqlCommand, etc. All of these classes offer asynchronous method calls along-side the standard synchronous versions. The async method name always starts with BeginXxx, and offers a corresponding EndXxx. For example, the SqlCommand class offers an ExecuteReader method, plus an async version of the method - BeginExecuteReader. To comply with the APM it also offers an EndExecuteReader method.
All delegates implement this pattern out-of-the-box. The all offer the standard Invoke method to execute the target method, and also offer the BeginInvoke and EndInvoke methods to execute the target method asynchronously.
This is the main reasons I love delegates so much.
Let's get down to it. One of the complexities of multi-threaded programming is figuring out when an async process completed its work. This is where the APM offers a great deal of help. There are three techniques to find out when a BeginInvoke is done: wait, poll and callback. I'll use a sample to describe the three techniques.
class PrimeCalc
{
public int GetNextPrime(int num)
{
int p = num + 1;
while(true)
{
if(IsPrime(p))
{
break;
}
p++;
}
return p;
}
}
Func< as our delegate:PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
public void WaitUntilComplete(int num)
{
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
IAsyncResult result = del.BeginInvoke(num, null, null);
// Do some other work here
// Suspend this thread until the async operation completes
int prime = del.EndInvoke(result);
}
public void Poll(int num)
{
PrimeCalc calc = new PrimeCalc();
Func<int, int> del = calc.GetNextPrime;
IAsyncResult result = del.BeginInvoke(num, null, null);
while (!result.IsCompleted)
{
// Do some other work here
}
// Get the result from the async operation
int prime = del.EndInvoke(result);
}
public void Callback(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);
}
private void CalcCompleted(IAsyncResult result)
Read more...
namespace AsyncProgrammingModel
{
class PrimeCalc
{
private List<int> primes;
public PrimeCalc()
{
primes = new ListList<int>();
primes.Add(2);
primes.Add(3);
}
public int GetNextPrime(int num)
{
int p = num + 1;
while (true)
{
// Create a list of all prime numbers up to p.
AddPrimesToList(p);
if (IsPrime(p))
{
break;
}
p++;
}
return p;
}
private void AddPrimesToList(int numberToTest)
{
int n = primes[primes.Count - 1] + 2;
while (n < numberToTest)
{
if (IsPrime(n))
{
primes.Add(n);
}
// Skip even numbers.
n += 2;
}
}
private bool IsPrime(int n)
{
bool foundDivisor = false;
bool exceedsSquareRoot = false;
int i = 0;
int divisor = 0;
// Stop the search if:
// there are no more primes in the list,
// there is a divisor of n in the list, or
// there is a prime that is larger than the square root of n.
while ((i < primes.Count) && !foundDivisor && !exceedsSquareRoot)
{
// The divisor variable will be the smallest
// prime number not yet tried.
divisor = primes[i++];
// Determine whether the divisor is greater than the square root of n.
if (divisor * divisor > n)
{
exceedsSquareRoot = true;
}
// Determine whether the divisor is a factor of n.
else if (n % divisor == 0)
{
foundDivisor = true;
}
}
return !foundDivisor;
}
}
}
In this post I'll discuss how delegates have evolved along with the evolution of .NET and C#. Specifically, how the introduction of anonymous methods and lambda expression helped make delegates more concise and useful.
This post is the first in a series of "Back-to-Basic" posts where I'll discuss basic .NET concepts and show how they have progressed with each new release of the .NET Framework.
I love delegates. If I had to come up with a list of my top 5 .NET features, delegates would definitely be high up on the list.
A Delegate, as defined by MSDN is:
"A type that defines a method signature, and can be associated with any method with a compatible signature. You can invoke (or call) the method through the delegate. Delegates are used to pass methods as arguments to other methods."
Delegates are first class citizens in the .NET framework and the C# language, and one of the fundamental types in the framework. They are used throughout the framework and enable important features such as events and asynchronous method calls.
In the old days, if we wanted a delegate that takes one parameter and returns void we had to declare one like this:
public delegate void DoWorkDelegate(string data);
Then we had to implement a method that conforms to the signature of the delegate:
private void DoSomeWork(string s)
{
// Do some work here
Console.WriteLine(s);
}
And finally, instantiate the delegate in our code:
DoWorkDelegate del = new DoWorkDelegate(DoSomeWork);In .NET 2.0 we could use a simplified syntax to instantiate the delegate:
DoWorkDelegate del = DoSomeWork;
The introduction of Generics in .NET 2.0 introduces a generic delegate Action. Action encapsulates a delegate that returns void and accepts 0 to 4 parameters (there are actually 5 generic Action types defined: Action, Action<T>, Action<T1, T2>, Action<T1, T2, T3>, Action<T1, T2, T3, T4>). So in the above example, we could have saved us the trouble of defining our own custom delegate "DoWorkDelegate" and instead used this:
Action<string> del = DoSomeWork;.NET 2.0 also introduced the concept of Anonymous Methods. This lets us avoid defining the "DoSomeWrok" method altogether and write it inline with the definition of the delegate:
Action<string> del = delegate(string s)
{
Console.WriteLine(s);
};
Finally, C# 3.0 introduced Lambda Expressions, which allow us to define the method inline like this:
Action<string> del = s =>
{
Console.WriteLine(s);
};
One more delegate worth mentioning is the Func delegate. Func was introduced in .NET 3.5 and just like its older brother, the Action, it encapsulates a delegate, but unlike Action Func encapsulates a delegate that takes 0 to 4 and returns a value. For example:
// Using Func we can replace this:
delegate int DoWorkDelegate(string data);
// with this:
Func<string, int> del;
In all the above samples (except for the last one) we end up with a "del" object. We could then use the "del" instance anywhere in our code to execute the "DoSomeWork" method. We could even pass "del" as an argument to other methods or objects that could also execute the same method:
// This is the verbose way:
del.Invoke("Do some work");
// This is a bit more concise
del("Do some work");
// This executes the method asynchronously
del.BeginInvoke("Do some work", null, null);
Next time on SapienCoder I will describe how to use delegates to implement Asynchronous programming patterns.
Read more...Probably not, but it will make us more productive during the tedious process of proving our humanhood to some random web server.
Anyone who's using the internet these days for anything more involved than reading news knows those annoying sets of garbled characters that appear at the end of checkout and registration pages.
Those are called CAPTCHAs (an acronym for "completely automated public Turing test to tell computers and humans apart") and they are designed to test that we, the users of the web site are in fact human. Now, I don't disagree with the motivation behind CAPTCHAs. Today's Web is infested with crawling bots and other malicious agents running around causing all kinds of mayhem. But, it just seems like a terrible waste of time for something that aught to be straight forward (how many times have you mistyped a CAPTCHA and had to enter it over and over again until the server acknowledged your humanhood?).
Luis von Ahn, the inventor of the CAPTCHA, said in an interview recently that by his estimates people spend an average of 10 seconds solving one of those CAPTCHA puzzles. Multiply that by the number of CAPTCHAs solved daily (aprox. 200 million) and you come to the staggering number of approximately 500,000 hours per day world wide. Astonishing when you think about it in these terms.
That's exactly why he came up with the brilliant idea of the reCAPTCHA.
There is a growing number of libraries and archives who are working on digitizing their entire collections. The process involves scanning the printed document (book, newspaper, magazine, historical document, etc.) to an image file, and then running a software called OCR (for Optical Character Recognition) that tries to recognize the words in the scanned image and turns them into a searchable text document. It turns out that the OCR software can't "read" every document with 100% accuracy. That's where the power of crowd-sourcing comes in.
ReCAPTCHA uses the words that computers can't decipher with OCR software (therefore can't be "read" by malicious robots) and displays them to humans. Each reCAPTCHA actually consists of two words, one was successfully recognized by the computer and the other wasn't. Each image is also shown to several people to verify the accuracy of the translation. If they agree on the translation the transcription is considered accurate and will be added to the text it originally came from. Currently more than 40,000 web sites world wide are using reCAPTCHA technology including some you might have heard of like Ticketmaster, Facebook and CraigsList. There are plug-ins for WordPress, Joomla, Drupal and many other popular web applications, as well as APIs for PHP, ASP.NET, Java, Perl, Ruby etc. The implementation is simple and there are lots of resources available for site developers.
Next time you run into those squiggly characters when commenting on a blog, or signing up for an online email account, make sure your time is not wasted on a standard CAPTCHA text. Let the site owners know your time could be spent on saving humanity, or at least it's written word.
Read more...
© Blogger template Blogger Theme II by Ourblogtemplates.com 2008
Back to TOP