Reputation: 823
I have a button click event that start an operation :
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 *****");
}
And the completed event of the backgroundworker :
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
processfinish = true;
Logger.Write("***** OPERATION ENDED *****");
}
And the timer1 tick event that start to work when its getting to the completed event:
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;
}
}
I want in my Logger text file to see something like:
Logger.Write("Operation Time Was: " + timepassed);
And timepassed will show minutes and second for example:
Operation Times Was: 05:21
Upvotes: 2
Views: 11429
Reputation: 9867
You can do
DateTime startTime = DateTime.Now;
Then after you are done processing do
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);
Here is the MSDN Documentation http://msdn.microsoft.com/en-us/library/8ysw4sby.aspx
The advantage to using this method (other than it specifically uses DateTime like you specified above) is that there is no timer running. You are not using any resources really here. You just grab the DateTime at the start of your process and at the end. Then subtract them to get the difference. To easy.
Upvotes: 1
Reputation: 602
// 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);
Upvotes: 1
Reputation: 3105
The simplest way (not the best since it isn't thread safe at all, so it won't work if you have 2 operations working at the same time)
Declare a private variable:
DateTime _start;
Then in your Diagnose_Click
method, assign a value to it:
_start = DateTime.Now;
And in your backgroundWorker1_RunWorkerCompleted
you can have the time elapsed like that:
TimeSpan elapsed = DateTime.Now - _start;
And you can write it directly in your log file using something like:
Logger.Write("Operation time was: " + elapsed.Minutes + "mn " + elapsed.Seconds + "s");
Upvotes: 2