使用宽范围锁和 WCF 回调进行多线程同步
我想做的是这样的——
我想对服务进行代理调用,并通过异步回调在单独的线程上接收数据......棘手的部分是我想让前台线程休眠,直到所有的数据已被检索。
我没有使用同步方法来执行此操作的原因是因为我正在为使用分页并以块的形式返回数据的 WCF 服务创建 API。
我希望我的客户端能够使用分页,但我不想将所有分页回调公开给我的 API...我希望它看起来好像 API 公开了同步数据检索方法。
我尝试使用私有静态信号量(因为它与线程无关),类方法和回调可以访问该信号量,并使用单个单元容量作为暂停执行的方法。
首先,我使用 Semaphore.WaitOne() 语句。
然后,我在前台线程中执行代理调用,服务创建一个处理数据检索的线程,并将控制权传递回客户端。
在客户端中,我立即使用第二个 Semaphore.WaitOne() 语句。 这应该暂停前台线程的执行,它确实做到了。 然后,一旦在单独的线程上执行“分页完成”回调,我就使用 Semaphore.Release() 但是前台线程永远不会遍历第二个信号量语句,它保持锁定状态,因此客户端冻结。
有什么想法我做错了吗,或者是否有其他更有效的锁定设计?
What I want to do is this--
I want to make a proxy call to a service and receive data on a separate thread through an asynchronous callback...the tricky part is that I want to make the foreground thread sleep until all of the data has been retrieved.
The reason I'm not using a synchronous method to do this, is because I'm creating an API for a WCF service that uses Paging and returns data in chunks.
I want my client to be able to use Paging, but I don't want to expose all of my Paging callbacks to my API...I want it to appear as though the API exposes a synchronous data retrieval method.
I've tried using a private static Semaphore (because it is thread agnostic,) that is accessible to the class methods and the callbacks, with a single unit capacity as a means to pause the execution.
First, I use a Semaphore.WaitOne() statement.
Then, I do a Proxy call in the foreground thread, and the service creates a thread that handles the data retrieval, and control is passed back to the client.
In the client, I immediately use a second Semaphore.WaitOne() statement.
This should pause the foreground thread execution, which it does.
Then, once the "Paging Completed" Callback is executed on a separate thread, I use Semaphore.Release()
But the foreground thread never traverses the second Semaphore statement, it stays locked and so the client freezes.
Any ideas what I am doing incorrectly, or is there another locking design that would be more effective?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要完成的任务是让前台线程等待数据收集线程,您可能需要考虑使用任务,这将允许您轻松完成此处描述的任务。
系统.线程.任务:
http://msdn.microsoft.com/en-us/library/dd235608.aspx
一些代码:
请务必查看文档中 t.Wait() 的详细信息。如果您的任务失败,您需要做好一些例外情况的准备。
If what you're trying to accomplish is having the foreground thread wait on data-gathering thread, you may want to consider using Tasks, which would allow you to easily accomplish what you've described here.
System.Threading.Tasks:
http://msdn.microsoft.com/en-us/library/dd235608.aspx
Some code:
Make sure to take a look at the details of t.Wait() in the documentation. There are some exceptions you will want to be ready for, in the event that your task fails.