Share via


when to use TimeSpan.Zero, TimeSpan.MinValue and TimeSpan.MaxValue

Question

Tuesday, October 16, 2012 10:06 AM

Hi All,

Can you please let me know what are the kinds of scenarios that I will be using TimeSpan.Zero, TimeSpan.MinValue and TimeSpan.MaxValue? And what is the difference between giving the sleep time for a thread as TimeSpan.Zero as compared to TimeSpan.MinValue? Also, if I give the sleep time for the thread as TimeSpan.MaxValue, will the thread sleep forever?

Please clatify.

Thanks,

Venkat

All replies (4)

Tuesday, October 16, 2012 10:15 AM âś…Answered | 1 vote

TimeSpan.MaxValue is more than 10 million days. TimeSpan.MinValue is around -10 million days. TimeSpan.Zero is 0 milliseconds.

Passing TimeSpan.MinValue to Thread.Sleep, or any other negative value to Thread.Sleep throws an exception except for -1 milliseconds, which means forever.

Passing TimeSpan.MaxValue to Thread.Sleep will not cause the thread to sleep forever... if you're willing to wait 29227 years, and the computer doesn't fail in between, the thread will awake eventually.


Tuesday, October 16, 2012 11:14 AM

Hi Louis,

Thank you for your time and detailed explanation.

Can you please let me know what then are the uses of TimeSpan.MinValue, TimeSpan.MaxValue and TimeSpan.Zero as I see that there is no practical use of using them in Thread.Sleep.

Thanks,

Venkat


Tuesday, October 16, 2012 1:27 PM | 1 vote

TimeSpan are not dedicated to be used as parameters to Thread.Sleep. They simply are time spans. It can be 5 seconds, 1 hour, or one thousand years. It is the type of the result when you substract two datetimes. It can be added to or substracted from a datetime to get another datetime.

Why TimeSpan.MaxValue is several thousand years? That structure's data is stored as ticks in a long. A long has a max value (9223372036854775807). If it had been stored as an int, the maximum span would have been of 2147483647 ticks, that's only 214 seconds.


Wednesday, October 17, 2012 4:48 AM

Hi Louis,

Thank you once again for your time and detailed explanation as to why the values are the way they are.

Thanks,

Venkat