Async WCF call to save thread?

南笙酒味 提交于 2020-01-02 06:45:07

问题


In another SO question, I was advised to send an asynchronous network request, rather than sending a synchronous request on a background thread. The reason was so that I don't waste a thread. I'm trying to understand how this is so.

This is the original approach. I can understand how there are two threads here. One is the main thread (1), and one is the background thread (Task.Run) (2) that makes the WCF call:

This is my sketch of the suggested approach. I'm trying to understand how a thread is saved. After the async WCF call, won't another thread be created for the callback from the async WCF call?

After thinking about this further, perhaps only one thread is used if callback processing isn't necessary?


回答1:


In your WPF client you likely have a OnClick somewhere in your client, where is the thread that is checking if the client was clicked or not?

The answer to that the OS itself is checking for the click then passing the message along to to the message pump which in turn invokes your function. The callback for the WCF function is like that, the OS itself is listening for the reply message and when it gets one it will send a signal that will find a free thread on the thread pool and execute the callback at that time.

The major difference between synchronously holding the thread and letting the callback method generate a thread at the end is the fact that the thread pool is a pool. When a thread in the thread pool finishes its work it does not get destroyed, it waits around a while to see if more work is available to be done and it will be reused to do that new work.

So the two choices are

  • Have 1 Thread sit there waiting doing no other work waiting for the function to unblock (Sync + thread)
  • Reuse an existing thread that has finished it's work already (or spawn a new one if none are waiting and we are below ThreadPool.GetMaxThreads()) when the OS tells us the information we where waiting for has shown up, give it the short task of handling the callback, then letting the thread go back in to the pool to do other work for other callbacks as they come in.


来源:https://stackoverflow.com/questions/19775997/async-wcf-call-to-save-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!