ConcurrencyMode.Multiple 和 WebOperationContext.Current 静态属性
我有一个带有 ConcurrencyMode = ConcurrencyMode.Multiple
选项的 WCF 服务。考虑到服务请求是并发处理的,我是否可以安全地读取传入请求 HTTP 标头并设置传出响应标头?我怀疑是因为 WebOperationContext.Current
是一个全局状态。它检查当前线程吗?
I have a WCF service with ConcurrencyMode = ConcurrencyMode.Multiple
option. Can I safely read incoming request HTTP headers and set outgoing response ones considering the fact that service requests are processed concurrently? I doubt because WebOperationContext.Current
is a global state. Does it check current thread?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
仅当您具有允许共享服务实例的实例时,
ConcurrencyMode.Multiple
才有意义。在 REST 服务的情况下,您很可能没有这样的实例(除非您使用单例服务),并且您不应该有这样的实例(因为 REST 服务不维护状态 - 所有状态都在请求中传输)。REST 服务使用每个请求实例化,每个请求都由一个新线程(来自线程池)和服务类的新实例自动提供服务。你根本不需要这个设置。
WebOperationContext.Current
从上下文内的私有线程静态变量检索当前上下文,因此它不会在线程之间共享。ConcurrencyMode.Multiple
make sense only if you have instancing which allows sharing the service instance. In case of REST service you most probably doesn't have such instancing (unless you are using singleton service) and you should not have such instancing (because REST service doesn't maintain state - all state is transferred in the request).REST service uses per request instancing and each request is served by a new thread (from thread pool) and new instance of the service class automatically. You don't need this setting at all.
WebOperationContext.Current
retrieves current context from private thread static variable inside the context so it is not shared among threads.好吧,既是又不是。 WebOperationContext.Current 属性确实是线程安全的。但是,返回的 WebOperationContext 对象的实例成员不是。这意味着您必须自己管理服务方法中的同步。
以下是 MSDN 关于 ConcurrencyMode.Multiple 的说法:
您的服务实现可能如下所示:
Well, both yes and no. The WebOperationContext.Current property is indeed thread safe. However the instance members of the returned WebOperationContext object are not. That means you'll have to manage synchronization in your service method yourself.
Here's what MSDN says about ConcurrencyMode.Multiple:
Your service implementation could then look something like this: