posts - 50, comments - 126, trackbacks - 6

My Links

News



View Marcin Celej's profile on LinkedIn

Archives

Post Categories

Generating Unique Id (Int64) in your application

I needed to generate some unique number in my application. I could use GUID, but it was too large for me (I need to keep lots of unique identifiers). I found something like this:

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
private static extern int QueryPerformanceFrequency(ref System.Int64 frequency);

[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
private static extern int QueryPerformanceCounter(ref System.Int64 performanceCount);

public static long GenerateUniqueId()
{
      System.Int64 id = 0;
      QueryPerformanceFrequency(ref id);
      QueryPerformanceCounter(ref id);
      return id;
}

This code generates Int64 (long) unique number (at least I hope it is unique). The uniqueness is in the scope of process. So two processes can generate the same number, but it should be always unique in a single process (I am not sure about two threads invoking the same GenerateUniqueId() method.

Print | posted on Friday, September 29, 2006 5:43 PM |

Feedback

Gravatar

# re: Generating Unique Id (Int64) in your application

Not a good idea. See:
http://blogs.msdn.com/oldnewthing/archive/2007/07/05/3695356.aspx
7/5/2007 2:34 AM | bahbar
Gravatar

# re: Generating Unique Id (Int64) in your application

I'm not an expert in Unique IDs, but why use something you "hope" to be unique if there are methods "guaranteed" to give you unique IDs?
7/5/2007 3:46 AM | Anon
Gravatar

# re: Generating Unique Id (Int64) in your application

So, if you need unique IDs only in one process and don't even care about thread-safety - why not just use a global variable that is incremented for every new value?
7/5/2007 10:54 PM | oliver
Gravatar

# re: Generating Unique Id (Int64) in your application

or if you do care - use InterlockedIncrement?
7/8/2007 5:29 AM | peterchen
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: