处理Windows服务中托管的WCF双工会话中的服务关闭

时间:2012-12-13 16:59:39

标签: .net wpf vb.net wcf

我有一个托管WCF服务的Windows服务,该服务向多个客户端广播信息。我想优雅地处理来自客户端的服务关闭,即检测到服务已消失或想要关闭,弹出消息并关闭应用程序。目前,如果我在关闭线关闭服务,我得到以下内容。

“ServiceHost关闭操作在00:00:09.9910000之后超时。这可能是因为客户端未能在规定的时间内关闭会话通道。”

问题:如何检测关闭请求并关闭客户端?

在客户端关闭服务后,我得到“Socket Exception ocurred现有连接被远程主机强行关闭”

这是密码。

If Not (_LivePricingHost Is Nothing) Then
    _LivePricingHost.Close()
    _LivePricingHost = Nothing
End If

这是我用来设置双工会话的类,我已经删除了样板配置代码和我正在筹集到客户端的事件。

Imports System.ServiceModel

Public Class NotificationCallback
    ' Implements LivePricingService.IMessageCallback
    Implements IDisposable

    Private _ns As LivePricingService.MessageClient

    Public Sub New()
        Dim context = New InstanceContext(Me)

        _ns = New LivePricingService.MessageClient(context)
        _ns.SubscribeForBroadcast()
        '    _ns.AddMessage("PING")
    End Sub

 #End Region

结束班

1 个答案:

答案 0 :(得分:1)

解决方案是在回调接口中添加“取消订阅”方法。然后客户可以取消订阅。 因此,当服务停止时,它会要求客户断开连接。

   Protected Overrides Sub OnStop()
        pollTimer.Stop()
        _LivePricingWCFService.UnsubscribeAll()
        If Not (_LivePricingHost Is Nothing) Then
            _LivePricingHost.Close()
            _LivePricingHost = Nothing
        End If
    End Sub

在WCF服务上

   Public Sub UnsubscribeAll()
        Try
            RemoveClosedSubscribers()

            For Each callback As IMessageCallback In _subscribers
                If DirectCast(callback, ICommunicationObject).State = CommunicationState.Opened Then
                    callback.ShutDown() 'request that the client disconnect
                    _subscribers.Remove(callback)
                End If
            Next
        Catch ex As Exception
            Logging.Logger.LogMessage(ex:=)
        End Try
    End Sub

并在客户端

Public Sub ShutDown() Implements LivePricingService.IMessageCallback.ShutDown
    _ns.Close()
    Globals.LastException = New Exception("The Live Pricing Serice has shut down.")

End Sub