1

我有一个 wcf 回调程序,它可以向客户端发送消息。

如果我尝试发送第二条消息,整个程序会冻结,我会收到超时异常。

这是服务器代码:

 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 { }
    }

这是回调接口:

 [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);

客户端会收到消息,但如果我第二次调用相同的方法,我会收到超时异常(设置为 1 分钟)。

我正在使用这个项目的代码(德语):

http://www.flexbit.at/blog/wcf-duplex-zwischen-windows-service-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);    
4

1 回答 1

1

尝试将 [CallbackBehavior(ConcurrencyMode = ConcurrencyMode. Reentrant , UseSynchronizationContext = false)] 更改为 [CallbackBehavior(ConcurrencyMode = ConcurrencyMode. Multiple , UseSynchronizationContext = false)]

于 2012-08-23T18:33:31.413 回答