我在文本框中有一些价值。我想在文本框中计算该值的时间。计算文本框中该值的长度。
值是布尔类型。它可以是1或0.我想计算每个值的时间跨度以及它们的差异。
答案 0 :(得分:0)
您发布的代码不多,但我会尝试一下。
我在代码中没有看到任何bool
变量。
您可能应该有一个保存当前状态的地方。
因为您将值写入TextBox
,您可以启动MMbach在该行之后建议的计时器:
sqlserver_status.Text = "Active";
// start timer here
如果您在代码中进一步更改此状态,则会停止计时器并检查已用时间。
你也可以使用StopWatch类。
它有一个名为Elapsed
的属性:
获取当前实例测量的总经过时间。
如果您需要在后台运行,我建议您去Timer
。
以下是使用System.Diagnostics.Stopwatch
实现的小型演示。
对这个问题有更多的认识。它总是取决于程序的结构,哪种实现更好或更差。
这是一个小型控制台应用程序,您可以在其中何时更改State
变量。它将监控您的决策过程。
public class TimeDemo
{
// Property to catch the timespan
public TimeSpan TimeOfState { get; set; }
// Full Property for the state
private bool state;
public bool State
{
get { return state; }
set
{
// whenever a new state value is set start measuring
state = value;
this.TimeOfState = StopTime();
}
}
// Use this to stop the time
public System.Diagnostics.Stopwatch StopWatch { get; set; }
public TimeDemo()
{
this.StopWatch = new System.Diagnostics.Stopwatch();
}
//Method to measure the elapsed time
public TimeSpan StopTime()
{
TimeSpan t = new TimeSpan(0, 0, 0);
if (this.StopWatch.IsRunning)
{
this.StopWatch.Stop();
t = this.StopWatch.Elapsed;
this.StopWatch.Restart();
return t;
}
else
{
this.StopWatch.Start();
return t;
}
}
public void Demo()
{
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
Console.WriteLine("Please press Enter whenever you want..");
Console.ReadKey();
this.State = !this.State;
Console.WriteLine("Elapsed Time: " + TimeOfState.ToString());
}
}
可以根据你的情况调整它。