views:

306

answers:

3

If I want to read or write a file I could use stream.BeginRead and stream.EndRead, but that requires callbacks and a LOT of ugly, complicated code using the asynchronous programming model.

Why would I want to use these asynchronous IO methods (that use the .NET threadpool behind the scenes) than write the same code in a synchronous style, and pass that to the thread pool. (Rather than chopping up my method with the callbacks.)

Update:

Some (good) responses indicate that using the APM saves me from creating a thread - which I agree with since new threads each have their own 2MB stack. But where does the 'BeginRead' and 'Endread' execute? The threadpool? Is reusing a thread which has already been allocated the only benefit?

+5  A: 

First of all, you should also look into the Event-based APM.

To answer your question, you're probably thinking about using a separate thread, and making synchronous calls. The other thread would block waiting for the calls to complete.

With the APM, there are no threads blocking at all. There is no draw from the Thread Pool. This is especially important for server applications like ASP.NET, since it means that a blocking thread won't be preventing requests from being processed.

John Saunders
I don't quite understand, are you saying that the once I start the 'BeginOperation' of the APM that no thread is actually used? But where does the code of the 'BeginOperation' actually execute then? Also, the 'EndOperation' callback has to be executed somewhere to - if not a separate thread where?
The Begin* code executes on the thread that calls it, queues some operation, and returns. When the operation is complete, the callback is called on a pool thread. Between Begin and callback, no thread is used. What for? Thread does nothing while it waits; "no thread" does nothing just as well.
John Saunders
+1  A: 

The advantage to using the asynchronous calls is that you're not wasting a thread blocking on I/O. Threads can be expensive, so in a situation where you're doing lots of I/O, it's key to use threads wisely.

That said, yes, the Begin-End APM is awful to have to use. If you do need non-blocking I/O and have the flexibility of using another language for part of your app, try F#. The 'async workflows' make it a breeze to write async code.

Brian
+2  A: 

Jeff Richter has a very clever and clean way to use APM.

Matt Davison