c# 线程池 - 如何返回值(使其与请求完全同步)
我有一个网络服务,需要从我的服务器获取数据。
请求需要在线程池内运行,如何将值返回给客户端?
I have a webservice that ask for data from my server.
The request needs to be run inside a thread pool, how do I return the value to the client?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
多线程根据其定义是异步的。为了取回值,您需要实现某种形式的回调(线程完成其操作时可以调用的方法),以便它可以传递值。
Multithreading is by its definition asynchronous. In order to get value back, you need to implement some form of callback (a method that the thread can call when it has finished its operation) so that it can pass the value.
您无法将初始请求的响应传递回客户。您必须返回一个令牌,客户端随后将使用该令牌轮询类上的另一个方法,以检查操作是否完成;如果操作完成,该方法返回结果,否则,返回一个结果以指示应该继续轮询。
如果您使用 .NET 4.0,我建议使用
Task< T>
class,并将其传递回您的客户端;您的客户端可以轮询结果、等待结果、完成后收到通知等。如果您不使用 .NET 4.0,那么我建议使用自定义
Delegate
,为其分配一个匿名方法/方法组,然后在该委托上调用BeginInvoke;这将返回IAsyncResult
实现您可以使用它来执行上述操作(轮询、等待等)。You can't pass a response back to your client on the initial request. You would have to return a token that the client would subsequently poll another method on your class with to check to see if the operation was complete; if the operation is complete, the method returns the result, otherwise, it returns a result to indicate that it should continue to poll.
If you are using .NET 4.0, I'd recommend using the
Task<T>
class, and passing that back to your client; your client can poll for the result, wait on it, get notification when it's done, etc.If you are not working with .NET 4.0, then I recommend using a custom
Delegate
, assigning an anonymous method/method group to it, and then calling BeginInvoke on the delegate; this will return anIAsyncResult
implementation which you can use to perform the operations mentioned above (polling, waiting, etc).