我有一个启动操作的按钮单击事件:
private void Diagnose_Click(object sender, EventArgs e)
{
processfinish = false;
timer2.Enabled = true;
timerCount = 0;
count = 0;
countBack = 5;
CreateZip.Enabled = false;
DriverVerifier.Enabled = false;
Diagnose.Enabled = false;
Diagnose.Text = "PROCESSING PLEASE WAIT";
if (this.backgroundWorker1.IsBusy == false)
{
this.backgroundWorker1.RunWorkerAsync();
}
Logger.Write("***** OPERATION STARTED *****");
}
背景工作者完成的事件:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
processfinish = true;
Logger.Write("***** OPERATION ENDED *****");
}
当timer1到达已完成的事件时开始工作的timer1 tick事件:
private void timer1_Tick(object sender, EventArgs e)
{
count++;
Diagnose.Text = "PROCESS HAS FINISHED" + " " + countBack--;
if (count == 6)
{
Diagnose.Text = "COLLECT INFORMATION";
Diagnose.Enabled = true;
CreateZip.Enabled = true;
ViewLogFile.Enabled = true;
DriverVerifier.Enabled = true;
timer1.Enabled = false;
}
}
我想在我的Logger文本文件中看到类似的内容:
Logger.Write("Operation Time Was: " + timepassed);
并且timepasssed将显示分钟和秒,例如:
操作时间是:05:21
答案 0 :(得分:5)
答案 1 :(得分:1)
最简单的方法(不是最好的方法,因为它根本不是线程安全的,所以如果你有2个操作同时工作它将无法工作)
声明私有变量:
DateTime _start;
然后在Diagnose_Click
方法中为其指定一个值:
_start = DateTime.Now;
在你的backgroundWorker1_RunWorkerCompleted
中,你可以有这样的时间:
TimeSpan elapsed = DateTime.Now - _start;
您可以使用以下内容直接在日志文件中编写它:
Logger.Write("Operation time was: " + elapsed.Minutes + "mn " + elapsed.Seconds + "s");
答案 2 :(得分:0)
你可以做到
DateTime startTime = DateTime.Now;
然后在完成处理后
DateTime endTime = DateTime.Now;
//This will give you something like 2hrs 15min or 15 days 11 hours 10 min ect
TimeSpan timePassed = endTime.Subtract(startTime);
以下是MSDN文档http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx
使用此方法的优点(除了它特别使用上面指定的DateTime)是没有计时器运行。你这里没有使用任何资源。您只需在流程开始时和结束时获取DateTime。然后减去它们以获得差异。为了方便。
答案 3 :(得分:0)
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
for (int i = 0; i < 1000; i++)
{
Thread.Sleep(1);
}
// Stop timing
stopwatch.Stop();
// Write result
Console.WriteLine("Time elapsed: {0}",
stopwatch.Elapsed);