开发者

Manage frequently called WCF connection

Maybe I'm missing something basic here, so please correct me if I am. I have a local ser开发者_如何学Cvice and a WinForms app that communicate via WCF, but I seem to end up with a lot of copies of this code in my application:

Public Shared Sub MyLocalMethod1()
    Dim tcpBinding As New NetTcpBinding
    tcpBinding.SendTimeout = New TimeSpan(0, 0, 5)

    Dim tcpFactory As ChannelFactory(Of MyWCFClass.MyWCFInterface) = New  _
                        ChannelFactory(Of MyWCFClass.MyWCFInterface)(tcpBinding, "net.tcp://localhost:4079")

    Dim ServiceWCFConnection As MyWCFClass.MyWCFInterface = tcpFactory.CreateChannel

    ServiceWCFConnection.MyWCFMethod1()

    tcpFactory.Close()

End Sub

I should probably be doing this in some kind of a helper class that creates the connection, lets my service use it, and then closes the connection, so I don't have multiple copies of this connection code. However, should I be leaving this connection open, or does it make sense to close it every time? The WinForm generally calls the service every few seconds, so it may make more sense to try and have a common copy that all these different calls can each access, instead of opening a closing a new connection each time.


It depends on your needs because both approaches are correct. You can wrap your channel creation code into some helper. You will have same functionality as you use at the moment with single place to edit your channel creation code (DRY principle). Usage of the service is slower because each call will create new TCP connection. Use some disposable helper class to represent your created connection.

If you decide to use single channel (proxy) for whole application you have to think about some new complexity. You are using Net.Tcp binding which creates transport session - TCP connection will live for long time. Moreover WCF service instance will live for the same time as the connection because default instancing mode is PerSession. So single service instance will handle all requests from your client = your service will became stateful. Also when you use opened channel for several calls you have to test state of the channel - network problem, server problem, timeout or unhandled exception will switch channel to Faulted state - such channel and related service instance cannot be used any more. You have to abort such channel and open new one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜