-2

I'm working with Milisecond and I've used it like

Timeout = (int)TimeSpan.FromMinutes(TimeoutVal).TotalMilliseconds

But I read on few places people are casting it to long instead of int? Why is that?

Roxy'Pro
  • 4,216
  • 9
  • 40
  • 102
  • 6
    `TotalMilliseconds` is a `double`, why do you want an integer value? Surely the answer to your question is because `int` isn't big enough. Are you really asking that? – DavidG Aug 28 '19 at 11:07
  • @DavidG What might happen if I leave it as it is (casted to int) ? – Roxy'Pro Aug 28 '19 at 11:09
  • 3
    If you leave it as-is, it will fail for any durations longer than around 600 hours. If none of your durations ever exceed 596 hours, it would work OK. – Matthew Watson Aug 28 '19 at 11:10
  • 1
    But the question is: why cast? – Kevin Kouketsu Aug 28 '19 at 11:12
  • If the value in the double overflows size of (int), the result will be an unusable int value, not an exception. – natt Aug 28 '19 at 11:20

1 Answers1

1

The only reason why I'd cast is if it's using an API that only allows an Int to be in timeout (e.g Thread.Sleep or Task.Delay), but in general rule you shouldn't, unless a) you don't mind if it overflows and cause "unexpected" behaviour or b) if it shouldn't overflow (like, you're using a small timeout).

In all other purposes, do not cast. Store it in double instead.

To calculate the max. number of hours in milliseconds you can store in a signed int32:

1s = 1000ms

1m = 60s

1h = 60m

Int32 max value: 2147483647

Then:

int totalSeconds = int.MaxValue / 1000;
int totalMinutes = totalSeconds / 60;
int totalHours = totalMinutes / 60;

The result would be 596.5232 hours.

Anyway, you shouldn't use a Timeout with such high values, instead, use a cancellation token. But again, it depends on the API you are working on.

Community
  • 1
  • 1
Lucca Ferri
  • 1,308
  • 12
  • 23