我正在尝试在给定的时间跨度内从客户端应用程序向我的WCF服务发送消息 我想知道的是我的WCF服务被客户击中的次数。
这是一个客户端应用程序:
var messages = new String[1];
messages[0] = "My simple request";
var client2 = new Operator();
var startTime = DateTime.Now;
var timeoutSpan = TimeSpan.FromMinutes(.06);
var count =0;
while ((DateTime.Now - startTime) <= timeoutSpan)
{
foreach (string message in messages)
{
txtRequest.Text = message;
sendMessageResult = client.sendMessage("02", txtRequest.Text);
count++;
}
}
// this counts how many request I sent
textBox1.Text = count.ToString();
// this shows the server side count
textBox2.Text = client2.TotalHits().ToString();
这是我的WCF服务应用程序
编辑:
public byte sendMessage(string strMsgId, string strMessage)
{
byte result = 1;
try
{
if (strMsgId == "02")
{
lock (_lock)
{
++_count;
}
// Logging-------
// Build timestamp string
var currentDateTime = DateTime.Now;
string timeStampString = currentDateTime.ToString("yyyy-MM-dd hhmmssfff");
// Build filename for Inbound messages, concat timestamp and .txt extension.
string debugFileName = "C:\\Inboundmessage" + " " + timeStampString + ".txt";
var inboundMessageLog = new StreamWriter(debugFileName, false, System.Text.Encoding.Default);
// Write to the file:
inboundMessageLog.WriteLine(DateTime.Now);
inboundMessageLog.WriteLine("Time = {0}", currentDateTime.ToString("yyyy-MM-dd hh:mm:ss:fff tt"));
inboundMessageLog.WriteLine("{0}{1}{2}", "Inbound Message:", Environment.NewLine, strMessage);
inboundMessageLog.WriteLine("{0}{1}", "count:", _count);
inboundMessageLog.Close();
// --------------
result = 0;
}
}
catch
{
//Failed
result = 1;
}
return result;
//这是一个计数方法
public int TotalHits()
{
return _count;
}
我在日志中看到计数是> 0但是为什么在客户端我在调用TotalHit方法时没有看到更改?
答案 0 :(得分:0)
一个问题: 你究竟想在这里实现什么目标?
解决方案有两个步骤: 步骤1:在IService启用会话
[ServiceContract()]
public interface IService
{
[OperationContract]
string SayHello(string toWhom);
[OperationContract]
int TotalHits();
}
步骤2:添加ServiceBehavior标记以启用Singleton
[ServiceBehavior(InstanceContextMode=InstanceContextMode.Single)]
public Service: IService
{
int count;
object _lock = new object();
string SayHello(string toWhom)
{
lock(_lock) { ++count; }
return "Hello, " + toWhom;
}
int TotalHits()
{
return count;
}
}