【发布时间】:2016-05-14 06:45:26
【问题描述】:
我使用 WCF Duplex 在服务器中订阅 WCF 的用户之间发送/接收消息。 WCF 有三种方法:Join(订阅)、Leave(取消订阅)和 SendAlert(从一个用户向其他用户发送消息)。以下是服务器端代码(AlertService in WCF duplex in server):
using System;
using System.Collections.Generic;
using System.ServiceModel;
namespace RahatWCF
{
[ServiceContract(Name = "AlertService",
Namespace = "RahatWCF",
SessionMode = SessionMode.Required,
CallbackContract = typeof(IAlertCallback))]
public interface IAlert
{
[OperationContract]
int JoinTheConversation(int userId);
[OperationContract(IsOneWay = true)]
void SendAlert(int senderUserId, List<int> recieversUserId, string caption, string messageText);
[OperationContract]
int LeaveTheConversation(int userId);
}
public interface IAlertCallback
{
[OperationContract(IsOneWay = true)]
void NotifyUserOfMessage(int senderUserId, List<int> recieversUserId, string caption, String messageText);
}
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single, InstanceContextMode = InstanceContextMode.PerCall)]
public class AlertService : IAlert
{
private static List<IAlertCallback> _callbackList = new List<IAlertCallback>();
public AlertService() { }
public int JoinTheConversation(int userId)
{
IAlertCallback registeredUser = OperationContext.Current.GetCallbackChannel<IAlertCallback>();
if (!_callbackList.Contains(registeredUser))
_callbackList.Add(registeredUser);
return _callbackList.Count;
}
public int LeaveTheConversation(int userId)
{
IAlertCallback registeredUser = OperationContext.Current.GetCallbackChannel<IAlertCallback>();
if (_callbackList.Contains(registeredUser))
_callbackList.Remove(registeredUser);
return _callbackList.Count;
}
public void SendAlert(int senderUserId, List<int> recieversUserId, string caption, string messageText)
{
_callbackList.ForEach(
delegate (IAlertCallback callback)
{
callback.NotifyUserOfMessage(senderUserId, recieversUserId, caption, messageText);
});
}
}
}
上面的代码是我在服务器端实现的 WCF Duplex。当用户登录应用程序时,我的 WCF 客户端应用程序会加入此 WCF;当用户从应用程序注销时,客户端应用程序会离开 WCF。问题是,如果用户突然终止应用程序并且没有从客户端应用程序注销,那么他/她以后无法向其他用户发送消息。我检查了这个问题,发现当用户登录(加入)并且没有注销(离开)时,在服务器中为用户创建了两个通道,并且 SendAlert 在这种情况下不再起作用。我该如何解决这个问题?
【问题讨论】: