Home > Blockchain >  Why can't I set the ReceiveTimeout property on System.Net.Sockets.Socket?
Why can't I set the ReceiveTimeout property on System.Net.Sockets.Socket?

Time:05-26

I'm attempting to set the ReceiveTimeout property an a System.Net.Sockets.Sockets object. I get no exceptions, but the value doesn't stick. Example:

      m_socket = new Socket(RemoteEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

      m_socket.ReceiveTimeout = TimeSpan.FromSeconds(1).Milliseconds;
      Debug.WriteLine($"Set ReceiveTimeout to {m_socket.ReceiveTimeout} ms");

Output:

Set ReceiveTimeout to 0 ms

I know there's a lot that goes on under the scenes when I set this property, but if there's a failure, it appears to be silent. Why doesn't the value stick?

CodePudding user response:

You're setting the value to 0, because that's the value of TimeSpan.Milliseconds for a 1-second timespan. The Milliseconds property is effectively "the sub-second millisecond component" - in the same way that (for example) the Minutes property for TimeSpan.FromHours(1.5) is 30, not 90. From the docs for TimeSpan.Milliseconds:

The millisecond component of the current TimeSpan structure. The return value ranges from -999 through 999.

If you want the total number of milliseconds in a TimeSpan, use the TotalMilliseconds property, then cast to int.

Example:

using System;

var timeSpan = TimeSpan.FromSeconds(1);
Console.WriteLine(timeSpan.Milliseconds); // Prints 0
Console.WriteLine((int) timeSpan.TotalMilliseconds); // Prints 1000
  • Related