我有一个wcf回调程序,它可以向客户端发送消息。
如果我尝试发送第二条消息,整个程序会冻结,我会得到一个timeoutexception。
这是服务器代码:
public void SendMessageToClient(string computerName, string message)
{
foreach (var session in connectedClients.Values)
{
if (session.ComputerName == computerName)
{
var asyncResult = session.Callback.BeginOnMessageReceived(message, new AsyncCallback(OnPushMessageComplete), session.Callback);
if (asyncResult.CompletedSynchronously)
CompletePushMessage(asyncResult);
}
}
}
void OnPushMessageComplete(IAsyncResult asyncResult)
{
CompletePushMessage(asyncResult);
}
void CompletePushMessage(IAsyncResult asyncResult)
{
var callbackChannel = (IServiceCallback)asyncResult.AsyncState;
try
{
callbackChannel.EndOnMessageReceived(asyncResult);
}
catch { }
}
这是Callback接口:
[OperationContract(IsOneWay = true, AsyncPattern = true)]
IAsyncResult BeginOnMessageReceived(string message, AsyncCallback acb, object state);
void EndOnMessageReceived(IAsyncResult iar);
这是客户端代码:
[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant, UseSynchronizationContext = false)]
public class ServiceHandler : IServiceCallback
{
public delegate void MessageReceivedHandler(string message);
public event MessageReceivedHandler OnMessageReceivedEvent;
public void OnMessageReceived(string message)
{
if (this.OnMessageReceivedEvent != null)
this.OnMessageReceivedEvent(message);
}
}
void callback_OnMessageReceivedEvent(string message)
{
setlb_info(message)
}
public void setlb_info(string wert)
{
if (this.lb_info.InvokeRequired)
{
setlb_infoCallback d = new setlb_infoCallback(setlb_info);
this.Invoke(d, new object[] { wert });
}
else
{
this.lb_info.Text = wert;
}
}
如果我试试这个:
Service.CurrentInstance.SendMessageToClient(client_name, message);
客户端将收到消息,但如果我第二次调用相同的方法,我会得到timeoutexception(设置为1分钟)。
我正在使用此项目的代码(德语):
http://www.flexbit.at/blog/wcf-duplex-zwischen-windows-sevice-und-gui-frontend/
我希望有人可以帮助我,因为如果这个功能无效,我就无法完成我的工作。
祝你好运
编辑:我忘记了客户端的代码: var callback = new ServiceHandler();
callback.OnMessageReceivedEvent += new ServiceHandler.MessageReceivedHandler(callback_OnMessageReceivedEvent);
var callbackInstanceContext = new InstanceContext(callback);
client = new ServiceClient(callbackInstanceContext);
client.Subscribe(System.Environment.MachineName);
答案 0 :(得分:1)
尝试更改 [CallbackBehavior(ConcurrencyMode = ConcurrencyMode。 Reentrant ,UseSynchronizationContext = false)] 至 [CallbackBehavior(ConcurrencyMode = ConcurrencyMode。 Multiple ,UseSynchronizationContext = false)]