-
Apr 14th, 2021, 12:15 PM
#1
Thread Starter
Lively Member
[RESOLVED] DateTime.Now.Substract
I index files using a BackgroundWorker. When finished I want to display the time the process lasted. Even when indexing takes less then one minute I get a time like:
63754024013,3167 sec.
Code:
ReadOnly dtt As Date
Dim dtt As Date = Now
BackgroundWorker1.RunWorkerAsync()
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Dim StopTime As Date = Now
Dim ts As TimeSpan = StopTime - dtt
PictureLoading.Visible = False
ToolStripStatusLabel1.Text = "Finished indexing in " + DateTime.Now.Subtract(dtt).TotalSeconds.ToString + " sec."
End Sub
-
Apr 14th, 2021, 12:28 PM
#2
Re: DateTime.Now.Substract
You have two declarations of dtt, one is a globally declared read-only variable whereas the other is (presumably) a locally scoped variable declared prior to calling RunWorkerAsync.
So what is happening is the globally declared variable has a value of the default date, which is 1/1/0001 12:00:00 AM. You can confirm this by setting up a breakpoint on this line and investigating the value:
Code:
Dim ts As TimeSpan = StopTime - dtt
To fix the issue, remove the ReadOnly keyword from the globally defined variable and don't define the local variable:
Code:
Private dtt As Date
Private Sub Main()
dtt = Date.Now
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
Dim StopTime As Date = Now
Dim ts As TimeSpan = StopTime - dtt
PictureLoading.Visible = False
ToolStripStatusLabel1.Text = "Finished indexing in " + DateTime.Now.Subtract(dtt).TotalSeconds.ToString + " sec."
End Sub
-
Apr 14th, 2021, 01:49 PM
#3
Re: [RESOLVED] DateTime.Now.Substract
In addition to this, you might want to look into the Stopwatch object.
Date manipulation the way you are doing it is likely to be adequate, but slightly fiddly. It's good enough if the resolution can be kind of coarse. The Stopwatch is good if you want a finer measurement. It may also perform slightly better, but you'd never see that difference, so it doesn't really matter. With the Stopwatch, you could create one at form scope, start it just prior to the call to RunWorkerAsync, then stop it in the RunWorkerCompleted event handler. The elapsed milliseconds would give you a pretty accurate timing down to the millisecond, which you could either report as such, or divide by 1000 to get a message that is equivalent to what you are currently showing.
My usual boring signature: Nothing
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|