Parameters for uniquely identifying objects at runtime?

I need to attach a unique identifier to objects at runtime. The identifier must be unique throughout the life of the application. I plan to do this with my private member variable in the base class of my object model. This variable will be set when the object is initialized, and the value will remain unchanged for the life of the object. No other object can have the same identifier for the duration of the application.

I can, of course, use System.Guid , but it costs 128 bits of memory for each object, and I would like to consume less resources. I tried using Int32 and initializing it using the System.Environment.TickCount property , but I do not get enough permission, and some objects end up with the same assigned value.

The documentation for TickCounter says that the TickCount property will roll back to a negative value after ~ 29, and then back to zero after another 29 days. I would change a higher resolution for a shorter roll over time.

Do I have other options that I don’t know about?

+5
source share
4 answers

. Interlocked.Increment, .

, 32- . - :

private static newObjectId = int.MinValue;

private static int GetNextId()
{
    return Interlocked.Increment(ref newObjectId);
}

.

+13

, ?

:

+3

- , 32- , , ?

No need to worry about TickCount or anything like that. The number "2" is unique among numbers; it differs from “1” and “3”, as well as from “1203 718”, if everything that you test is equivalent.

+2
source

All Articles