【发布时间】:2017-03-08 11:49:37
【问题描述】:
我遇到了 WCF 双工服务问题。
这是我的服务接口:
[DeliveryRequirements(RequireOrderedDelivery = true)]
[(CallbackContract = typeof(IMyNotification), SessionMode = SessionMode.Required)]
public interface IMyService
{
[OperationContract]
void StartSomething();
...
}
服务实现:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class MyService : IMyService
{
...
}
回调接口:
[DeliveryRequirements(RequireOrderedDelivery = true)]
public interface IMyNotification
{
[OperationContract (IsOneWay=true)]
void NotificationAvailable(Notification notification);
}
客户端回调实现:
[CallbackBehavior (ConcurrencyMode = ConcurrencyMode.Multiple, UseSynchronizationContext = false)]
class MyServiceCallback : IMyNotification
{
public void NotificationAvailable(Notification notification)
{
lock (_NotificationLock)
{
// process notification...
}
}
}
假设 StartSomething() 方法启动某种设备,并且在该方法内部,设备从“正在启动”和“就绪”两种状态进入。当状态更改时,通过 MyServiceCallback 类中的 NotificationAvailable 通知客户端。
问题是有时在 NotificationAvailable 方法消息中 即使设置了已订购的交付,也没有以正确的顺序收到(正确的顺序是“开始”->“就绪”,但回调接收“就绪”>“开始”)。
这通常发生在第一次调用 StartSomething() 方法时。这似乎是某种线程竞争条件。当我在 MyServiceCallback 上设置 ConcurrencyMode = ConcurrencyMode.Single 时,问题就消失了。
解决此问题的正确方法是什么?
【问题讨论】:
标签: c# multithreading wcf nettcpbinding