简体   繁体   English

用于 VB (COM) 客户端的 WCF 单一服务实例

[英]WCF single instance of service for VB (COM) client

I created a WCF service, and want to be used by multiple VB clients.我创建了一个 WCF 服务,并希望被多个 VB 客户端使用。

I need only a single instance of the service, even if multiple clients start, use it, or stop.我只需要一个服务实例,即使有多个客户端启动、使用或停止。

But the result seems to be against my expectation.但结果似乎出乎我的意料。 My code is:我的代码是:

WCF service: WCF 服务:

namespace xComm
{
    [ServiceBehavior(
        InstanceContextMode = InstanceContextMode.Single,
            ConcurrencyMode = ConcurrencyMode.Single)]
    public class SvcACS : ISvcACS
    {
        private int m_nCounter = 0;

        public int CounterUp()
        {
            m_nCounter++;
            return m_nCounter;
        }
        public int CounterGet()
        {
            return m_nCounter;
        }

    }
}

After building the WCF service, I can use it by COM reference from VB application, as the following one, a simple form application calling CountUp method and checking return value:构建 WCF 服务后,我可以通过 VB 应用程序中的 COM 引用来使用它,如下所示,一个简单的表单应用程序调用 CountUp 方法并检查返回值:

Option Explicit

Dim svcAcs As xComm.ISvcACS

Private Sub btnCmd_Click(Index As Integer)
    Dim nW1 As Integer
    
    nW1 = svcAcs.CounterUp()
    lblCounter.Caption = CStr(nW1)
End Sub

Private Sub Form_Load()
    Set svcAcs = New xComm.svcAcs                   
End Sub

I started for example 2 VB clients and press the btnCmd button respectively.例如,我启动了 2 个 VB 客户端并分别按下 btnCmd 按钮。 What I want is:我想要的是:

  1. client 1's btnCmd is clicked: client 1's lblCount shows 1客户端 1 的 btnCmd 被点击:客户端 1 的 lblCount 显示 1
  2. client 2's btnCmd is clicked: client 2's lblCount shows 2客户端 2 的 btnCmd 被点击:客户端 2 的 lblCount 显示 2
  3. client 1's btnCmd is clicked: client 1's lblCount shows 3 ...客户端 1 的 btnCmd 被点击:客户端 1 的 lblCount 显示 3 ...

But the result turned out that clients are serviced independently, instead of by using a single instance of service, which the counter would have been shared.但结果证明,客户端是独立服务的,而不是使用单个服务实例,而计数器本来是共享的。

I have used InstanceContextMode.Single, is this not enough?我用过InstanceContextMode.Single,这还不够吗?

Thanks in advance.提前致谢。

Ting

This is just a speculation on my part, but the Instancing article notes, that这只是我的猜测,但Instancing 文章指出,

Single: A single instance of the service class handles all client requests for the lifetime of the application .单个:服务类的单个实例处理应用程序生命周期内所有客户端请求。

(Emphasis mine) (强调我的)

Which to me sounds that because you are using two applications, each creating its own instance of the service, you experience the expected behavior.对我来说这听起来是因为您正在使用两个应用程序,每个应用程序都创建自己的服务实例,您会体验到预期的行为。 So I assume you need to persist & restore the return value between calls and share it between the service instances.因此,我假设您需要在调用之间保持并恢复返回值并在服务实例之间共享它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM