无法显示来自客户端Web表单的计数

时间:2014-03-04 21:56:00

标签: c# wcf

我正在尝试显示从客户端Windows窗体应用程序调用方法的次数。以下是服务和客户端的定义方式。

在我的日志文件中,我看到每个方法调用都会增加计数,但是我无法从客户端表单中看到我放入列表的总计数。

IOperator
{

    SendMessage(string strMsgId, string strMessage);

    [OperationContract] 
    List<int> GetCount();
}
  [ServiceBehavior(Namespace = "http://X.org/MessageService/"]  
  Operator: IOperator
  {

    private  List<Int32> TotalCount = new List<Int32>();

   public static List<int> TotalCount
    {
        get { return _totalCount; }
        set { _totalCount = value; }
    }
SendMessage(string strMsgId, string strMessage) 
    {
    if (strMsgId == "02")
        {
            lock (_lock)
            {
                ++_count;
                TotalCount.Add(_count);
            }
            string debugFileName = "C:\\Test.txt";
            // Write to the file:
            inboundMessageLog.WriteLine("{0}{1}", "Inbound Message:", strMessage.Substring(549, 27));
            inboundMessageLog.WriteLine("{0}{1}", "count:", _count);
            inboundMessageLog.WriteLine("{0}{1}", "Total Count:", TotalCount.Count);

            result = 0;
        }
    }

    public List<int> GetCount()
    {
        return TotalCount;
    }
}

编辑

我想在每个给定时间内保存一些会话中的总计数,并在我的文本框中获取该计数。我想要总数而不管客户端数量。 TotalCount是静态的,定义为私有静态List _totalCount = new List();使用getter TotalCount。

我没有为服务明确定义InstanceContextMode,是的,totalcount显示为0.

客户端:

 var clientA = new SendServiceReference.SendService();
  Operator clientB = new Operator();

 while ((DateTime.Now - startTime) <= timeoutSpan)
        {

                // Send request to external service and all the requests will be logged to my service since I don't have control over the external service.
              sendMessageResult = clientA.SendMessageToExternalService("01", txtRequest.Text);

        }
  //display the total request received from client A for the give time span
responseCount.Text = clientB.GetCount().Count.ToString();

1 个答案:

答案 0 :(得分:0)

您没有指明您正在使用的绑定,或者您是否明确定义了服务的InstanceContextMode,但是根据您描述的行为,它听起来像是默认的PerSession,这为每个客户创建了一个新的服务实例。

最有可能发生的是您正在创建一个客户端来发送消息,这就是您看到计数器递增的原因。然后创建第二个客户端(client2 = new Operator();,它创建该服务的另一个实例,这意味着TotalCount为0或null(因为您没有表明您获得一个错误,我猜测计数TotalCount是0)。换句话说,你不再访问/使用增加计数的服务实例,而是一个全新的实例具有自己的TotalCount字段/属性的服务。

根据您的要求/需求,有几种方法可以解决这个问题。

如果无论客户端数量多少都需要总计数,您可以将TotalCount设为静态,也可以将InstanceContextMode设置为Single。我不鼓励使用InstanceContextMode.Single,因为这会导致缩放问题,并使用静态TotalCount

如果您需要每个客户端的总计数,那么您将需要使用在循环中进行10次调用的同一客户端来调用GetCount()。例如:

Operator client1 = new Operator();

for (int i =0; i < 10; i++)
{
    // Send your messages
}

responseCount.Text = client1.GetCount().Count.ToString();

有一篇关于CodeProject的文章,其中包含可能对您有用的3种不同InstanceContextModes的插图:Three ways to do WCF instance management