views:

64

answers:

3

I'm referring to this answer where it says it's not required, there are few specific assumptions though. That question is general.

  • I'm using C#
  • Asynchronous process is doing nothing but just calling an external API and waiting for the reply.
+2  A: 

Yes, a Pool Thread is used. But that thread is not hanging around waiting for the external device. The thread is re-used and a(nother) thread is called upon when the I/O is completed.

See I/O Asynchronous Completion on MSDN.

Henk Holterman
+3  A: 

Your question is too general. The Windows API has specific support for asynchronous I/O without using a thread, check the docs for ReadFile() for example. The lpOverlapped argument controls this. The ReadFileEx() function allows specifying an I/O completion callback. This is well covered by the .NET framework classes.

Calling a slow external API function is not covered by this mechanism, you need to spin up your own thread.

Hans Passant
+1  A: 

Generally yes, but there is at least one exception I can think of. To initiate an asynchronous operation you must transfer the operation outside of the context of the caller. What I mean by that is that the caller should not block waiting for the operation to complete. That usually means that the operation has to move to a newly created thread, a thread from the ThreadPool, an IO completion port, another process, or the like.

I said there was one exception that came to mind. If we slightly pervert our definition of asynchronous we can allow for scenarios in which the initiator does not block waiting for the operation to complete without actually moving the operation to another thread. The best example of this is the UI message pump. In .NET it is easy enough to call Control.BeginInvoke from the UI thread itself to post the execution of a delegate on the same thread. The initiator clearly would not block waiting for the delegate to complete and yet the delegate would eventually start executing on the same thread. This is definitely a perversion of what we typically think of the term asychronous because in this scenario the operation blocks until the caller completes instead of the other way around.

Brian Gideon
Can you please site a reference for the exception you suggested if you have or if anyone other than me can up vote it.
Ismail
@Ismail: The MSDN documentation for the `Control.BeginInvoke` spells this out almost exactly. It even mentions that you can call `BeginInvoke` from the *same* thread hosting the control and that the delegate will be executed "asynchronously" on *that* thread.
Brian Gideon
How can i do similarly (i.e. without starting a new thread) for calling external web service?
Ismail
@Ismail: Its not possible. The mechanisms for calling web services asynchronously do not have a message loop and thus cannot suffer from the problem I described as the lone exception.
Brian Gideon
Thanks for the explanation.
Ismail