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 rep开发者_如何学运维ly.
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.
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.
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.
精彩评论