我有一个WCF服务,它在服务器位置创建许多文件,根据给定的参数对种子文件进行各种计算。问题是,当2个或更多的客户端试图对同一个种子文件进行计算时,它会返回错误。原因很简单,就是多个用户同时进行读/写访问。所以我想在WCF中创建一个用户请求队列,从服务器一次计算一个,并返回计算响应给用户。问题是我不知道该怎么做。
我之前没有在WCF中实现任何请求队列技术。有人知道如何在WCF服务中实现这一点吗?我不能执行线程,因为计算依赖于文件I/O,所以一次处理一个请求只是目前的一种解决方案。
任何教程或视频教程将是高度赞赏。
我终于做到了。在这里,我为其他可能不熟悉WCF请求队列的用户发布了我的解决方案。首先,我们需要在WCF主机文件中实现节流设置。节流可以通过两种方式完成(任何一种方式都可以):
- 配置文件
配置文件中的Throttling设置如下:
(行为)[serviceBehaviors] [behavior name="throttlingBehavior"] [serviceThrottling maxConcurrentCalls="3" maxConcurrentInstances="3" maxConcurrentSessions="100"/] [/behavior][/serviceBehaviors][/行为]
或代码中的节流设置
using (ServiceHost host = new ServiceHost(typeof(SimpleService.SimpleService)))
{
ServiceThrottlingBehavior throttlingBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = 3, MaxConcurrentInstances = 3, MaxConcurrentSessions = 100 };
host.Description.Behaviors.Add(throttlingBehavior);
host.Open();
Console.WriteLine("Host started @ " + DateTime.Now.ToString());
Console.ReadLine();
}
使用上述节流设置,最多处理3个并发调用。除了maxConcurrentCalls属性,maxConcurrentInstances和maxConcurrentSessions也可能影响并发处理的调用数量。
在定义了节流行为之后,我们需要在服务契约中定义并发模式,如下所示:[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall,ConcurrencyMode=ConcurrencyMode.Multiple)]
public class Service:IService
{...
有了这些设置,我们可以很容易地在WCF服务中获得请求排队。