我有一个WCF双向服务的问题。
这是我的服务接口:
服务实现:
回调接口:
客户端回调实现:
假设StartSomething()方法启动某种设备,在该方法内部,设备从“启动”和“就绪”两个状态之间转换。当状态改变时,客户端通过MyServiceCallback类中的NotificationAvailable接收通知。
问题是,即使设置了有序传递(正确的顺序应该是“启动”->“就绪”,但回调却接收到“就绪”->“启动”)有时在NotificationAvailable方法中收到的消息顺序不正确。
这通常发生在第一次调用StartSomething()方法时。看起来像是某种线程竞争条件。当我在MyServiceCallback上设置ConcurrencyMode = ConcurrencyMode.Single时,问题消失了。
解决此问题的正确方法是什么?
这是我的服务接口:
[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时,问题消失了。
解决此问题的正确方法是什么?