在 .NET 应用程序中捕获从客户端调用服务器的开始和结束时间
本文关键字:服务器 开始 时间 结束 调用 客户端 应用程序 NET | 更新日期: 2023-09-27 18:37:25
如何在客户端传递一个参数来获取开始和结束时间,这是向服务器调用此调用所需的时间,因为服务器存储了一些信息并且它不能直接与客户端通信,但客户端可以请求。我需要获取最短、最长和平均时间,并将该信息显示在后台客户端的 UI 中,我可以在其中查看每个用户调用服务器所需的时间。
#region Timer Handlers
private void OnTimer(object sender, ElapsedEventArgs e)
{
Ping();
}
protected virtual void Ping()
{
try
{
//Created Date Time to
DateTime _Now = DateTime.Now;
var incomingRequests = GetInboundEcounterInfoForClientCommand.CheckForNewInboundRequests(
_sessionKey, _userName, _machineName, _openedPatients);
DateTime NowAgain = DateTime.Now;
TimeSpan difference = NowAgain - _Now;
PaceartLoggingService.LogInfo()
if (incomingRequests != null)
{
incomingRequests.ForEach(request => _requests.Enqueue(request));
if (_requests.Count > 0)
{
InvokeInboundDataAvailible();
}
}
}
catch (Exception ex) // this should only happen when the server goes down
{
PaceartLoggingService.LogError(typeof(GetInboundEcounterInfoForClientCommand), ex);
}
}
private void InvokeInboundDataAvailible()
{
if (InboundDataAvailible != null)
{
InboundDataAvailible(this, EventArgs.Empty);
}
}
#endregion
我没有完全理解你的问题,我假设你想测量一个长时间运行的方法的执行时间。该方法位于服务器上,您在客户端上调用它。
您可以在两个地方这样做。
第一种方法:你可以启动一个计时器,调用方法,获取结果,停止计数器,现在你根据客户端有了执行时间。这种方法不是很准确,因为您也在计算连接时间,我的意思是如果该方法需要 10 秒,连接需要 2 秒,您将获得 12 秒。
第二种方法:您可以使用相同的服务器上计时器方法。从客户端调用服务器方法,服务器启动计时器,执行长时间作业,停止计时器,最后将经过的时间作为结果传递回客户端。这种方法更准确一些,因为不会计算连接时间。
public class Client
{
public void CallServerMethod_ApproachOne()
{
Server s = new Server();
var sw = System.Diagnostics.Stopwatch.StartNew();
s.LongLongTimeMethod_ApproachOne();
sw.Stop();
MessageBox.Show(sw.ElapsedMilliseconds.ToString());
}
public void CallServerMethod_ApproachTwo()
{
Server s = new Server();
var elapsedMilliseconds = s.LongLongTimeMethod_ApproachTwo();
MessageBox.Show(elapsedMilliseconds.ToString());
}
}
public class Server
{
public void LongLongTimeMethod_ApproachOne()
{
//this is just a way to waste time, your real work is done here
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(new Random().Next(1, 10)));
return;
}
public long LongLongTimeMethod_ApproachTwo()
{
var sw = System.Diagnostics.Stopwatch.StartNew();
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(new Random().Next(1, 10)));
sw.Stop();
return sw.ElapsedMilliseconds;
}
}
为了记录最短、最长和平均时间,您可以将值保存在某种列表或数组中。
最后,使用 DateTime 获取执行时间不是一个合适的解决方案。最好的解决方案是使用分析器,你可以谷歌它。祝你好运