简体   繁体   English

异步WCF调用以保存线程?

[英]Async WCF call to save thread?

In another SO question , I was advised to send an asynchronous network request, rather than sending a synchronous request on a background thread. 另一个SO问题中 ,建议我发送异步网络请求,而不是在后台线程上发送同步请求。 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: 一个是主线程(1),一个是后台线程(Task.Run)(2),该线程进行WCF调用:

在此处输入图片说明

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? 异步WCF调用之后,是否将为异步WCF调用的回调创建另一个线程?

在此处输入图片说明

After thinking about this further, perhaps only one thread is used if callback processing isn't necessary? 进一步考虑之后,如果不需要回调处理,也许仅使用一个线程?

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? 在WPF客户端中,您的客户端中某处可能有一个OnClick ,用于检查客户端是否被单击的线程在哪里?

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. WCF函数的回调就是这样,操作系统本身正在侦听答复消息,当它收到消息时,它将发送一个信号,该信号将在线程池中找到一个空闲线程并在那时执行回调。

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) 有1个线程坐在那里,等待其他任何等待该功能解除阻塞的工作(同步+线程)
  • 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. 当OS告诉我们显示了我们在哪里等待的信息时,请重用一个已经完成工作的现有线程(如果没有正在等待的线程,或者在ThreadPool.GetMaxThreads()以下,则产生一个新ThreadPool.GetMaxThreads() ,以完成简短的任务处理回调,然后让线程回到池中为其他回调做其他工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM