Prev | Current Page 346 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"


180 CHAPTER 6 Implementing iterators the easy way
void AfterGetRates(IAsyncResult result)
{
IAsyncResult holdingsAsync = (IAsyncResult)result.AsyncState;
StockRates rates = StockService.EndGetRates(result);
Holdings holdings = DbService.EndGetStockHoldings
(holdingsAsync);
OnRequestComplete(ProcessStocks(stocks, rates));
}
This is much harder to read and understand??”and that??™s only a simple version! The
coordination of the two parallel calls is only achievable in a simple way because we
don??™t need to pass any other state around, and even so it??™s not ideal. (It will still block
a thread waiting for the database call to complete if the second web service call completes
first.) It??™s far from obvious what??™s going on, because the code is jumping around
different methods so much.
By now you may well be asking yourself where iterators come into the picture. Well,
the iterator blocks provided by C# 2 effectively allow you to ???pause??? current execution
at certain points of the flow through the block, and then come back to the same place,
with the same state. The clever folks designing the CCR realized that that??™s exactly
what??™s needed for something called a continuation-passing style of coding. We need to
tell the system that there are certain operations we need to perform??”including starting
other operations asynchronously??”but that we??™re then happy to wait until the
asynchronous operations have finished before we continue.


Pages:
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358