CancellationTokenSource with TimeSpan.From... or Constant time value?

193 Views Asked by At

Are there any advantages in using TimeSpan.FromMilliseconds(1000) instead using a constant value when creating a CancellationToken?

CancellationTokenSource ctsTs = new(TimeSpan.FromMilliseconds(1000));
CancellationTokenSource ctsConst = new(1000);
3

There are 3 best solutions below

1
jingwei jiang On

It tells the reader the unit of timespan is millisecond, but 1000 doesn't.

0
Rufus L On

The helpful thing about using TimeSpan is that it tells the reader what the number represents (a span of time).

Another benefit of using TimeSpan is that you don't have to pass milliseconds - you can pass something more readable (at least to new programmers), like seconds:

CancellationTokenSource ctsTs = new(TimeSpan.FromSeconds(1));
0
George Tsouvaltzis On

From .NET side, there is no difference between the two. CancellationTokenSource source code In the end it just takes TimeSpan's TotalMilliseconds and that's how it's initalized.

by using Timespan.FromMilliseconds it's just more clear for the user/reader that it uses Milliseconds and the number 1000 is represented as ms. However, if you just leave 1000, user will have to take additional action in order to figure out if 1000 means minutes, seconds, or milliseconds. if you prefer not to use Timespan at all, another option would be to introduce separate constant for number 1000 and give it a more descriptive name.