C#如何强制等待连接到WCF服务

时间:2017-12-18 16:28:31

标签: c# multithreading wcf

我有一个作为本地SYSTEM运行的服务,它使用用户凭据启动另一个应用程序。 第二个应用程序只是一个托盘图标,向用户显示使用回调方法收到的字符串的气球提示。第二个应用程序以双工模式连接到WCF。

我的问题是,由于某种原因,在方法Main的末尾完成了与WCF的连接。所以我不能在执行后立即向应用程序发送回调消息,包含在最后一行" kiosk.MyStart(args);"中。那里的回调仍然指向null。

我知道如何解决这个问题?

static void Main(string []args)
{
    if (Environment.UserInteractive)
    {
         // Start the WCf service
         var host = new ServiceHost(typeof(WcfService));
         host.Open();

         //Launch the Kiosk Agent which connects to the WCF
         bool ret = ProcessAsUser.Launch("C:\\Program Files (x86)\\KIOSK\\KioskAgent.exe");
         WinService kiosk = new WinService(args);
         // some checks and a welcome message is sent to the user.
         kiosk.MyStart(args);

         //...
         //...
    }
}

编辑:为了澄清一点,在kiosk.MyStart方法中,我尝试执行回调以显示欢迎消息,但回调仍为NULL。 因此,我认为客户端由于任何原因未正确启动,我再次启动它......

            if (WcfService.Callback != null)
                WcfService.Callback.UIMessageOnCallback(UIMessage);
            else
                ProcessAsUser.Launch("C:\\Program Files (x86)\\KIOSK\\KioskAgent.exe");

1 个答案:

答案 0 :(得分:1)

在回调方法上添加一个try catch块,如果客户端无法访问它,则可以取消订阅它。也是一种好的做法,向您的客户发送keepalive消息,以检查它是否可用。

private void InformClient(ClientInfo clientInfo)
{
    var subscribers = this._subscriberRepository.GetAll();
    foreach (var subscriber in subscribers)
    {
        try
        {
            if (subscriber.Callback.FireInformClient(clientInfo));
            {
                //If subscriber not reachable, unsubscribe it
                this._subscriberRepository.Unsubscribe(subscriber.ClientId);
            }
        }
        catch (Exception exception)
        {
            //If subscriber not reachable, unsubscribe it
            this._subscriberRepository.Unsubscribe(subscriber.ClientId);
            Log.Error(nameof(InformClient), exception);
        }
    }
}

IClientCallback

public interface IClientCallback
{
    [OperationContract]
    bool FireInformClient(ClientInfo clientInfo);
}

如果您有更多订阅者,例如终端,则服务器会创建一个subscriberRepository来管理所有订阅者。

var callback = OperationContext.Current.GetCallbackChannel<IClientCallback>();
if (this._subscriberRepository.Subscribe(clientId, callback))
{
    return true;
}