Can DateTime tear in a 64 bit environment?

From the ECMA specification section “I.12.6.6 Atomic reads and writes”

A conforming CLI shall guarantee that read and write access to properly aligned memory locations no larger than the native word size (the size of type native int) is atomic (see §I.12.6.2) when all the write accesses to a location are the same size. Atomic writes shall alter no bits other than those written. Unless explicit layout control (see Partition II (Controlling Instance Layout)) is used to alter the default behavior, data elements no larger than the natural word size (the size of a native int) shall be properly aligned. Object references shall be treated as though they are stored in the native word size.

A native int is a IntPtr in C#.

So long as sizeof(IntPtr) >= sizeof(DateTime) is true for the runtime environment (aka: running as 64 bit), and they don’t alter the internal structure to be explicit layout with misaligned bytes instead of the [StructLayout(LayoutKind.Auto)] it currently has, then reads and writes of a DateTime struct (or any other struct that follows those rules) are guaranteed to be atomic by the ECMA specification.

You can verify that by running the following code in a 64-bit environment:

public unsafe static void Main()
{
    Console.WriteLine(sizeof(DateTime)); // Outputs 8
    Console.WriteLine(sizeof(IntPtr)); // Outputs 8
    Console.WriteLine(sizeof(ulong)); // Outputs 8
}

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)