Beware of stack overflows in asynchronous calls

This one bit me not too long ago, and I thought I'd share it to help ease other's pain if the run into it as well...

I was playing around with some product code, and one of the unit tests started failing with a stack overflow error. When I ran it by itself, it wouldn't repro; running the whole suite would usually repro it, but again not always.

Burnt a bunch of time looking into it, and here's the diagnosis.

It turns out that the test in question was using the asynchronous APIs of the ADO.NET Data Services client-side DataServiceContext. After making repeated calls to the same server, some of them were finishing synchronously, firing the callback before unwinding the stack; at that point, the test followed up with additional asynch requests, which were also finished before returning, and not too long after that I ran out of stack space.

The fix in my case was to schedule the next piece of work to be done rather than executing it immediately in the callback. Whenever you're doing these sorts of things, SynchronizationContext is your friend, which in Silverlight is implemented in DispatcherSynchronizationContext. The Post method allows you to queue up a piece of work (execute asynchronously).

Enjoy!