Geeks With Blogs
Marcin Celej blog

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.

Posted on Friday, September 29, 2006 5:43 PM | Back to top


Comments on this post: Generating Unique Id (Int64) in your application

# re: Generating Unique Id (Int64) in your application
Requesting Gravatar...
Not a good idea. See:
http://blogs.msdn.com/oldnewthing/archive/2007/07/05/3695356.aspx
Left by bahbar on Jul 05, 2007 2:34 AM

# re: Generating Unique Id (Int64) in your application
Requesting Gravatar...
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?
Left by Anon on Jul 05, 2007 3:46 AM

# re: Generating Unique Id (Int64) in your application
Requesting Gravatar...
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?
Left by oliver on Jul 05, 2007 10:54 PM

# re: Generating Unique Id (Int64) in your application
Requesting Gravatar...
or if you do care - use InterlockedIncrement?
Left by peterchen on Jul 08, 2007 5:29 AM

Your comment:
 (will show your gravatar)


Copyright © Marcin Celej | Powered by: GeeksWithBlogs.net