views:

89

answers:

4

I need to build a unique filename in a multithreaded application which is serializing some data on the disk. What approach could I use to ensure a unique name. The app was not multithreaded before and was using Ticks. When using multiple threads, it failed much faster than I expected. I now added the CurrentThreadId to the filename, and that should do it

string.Format("file_{0}_{1}.xml", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId)

Is there any "smarter" way of doing this?

+8  A: 

What about Guid.NewGuid() instead of the thread id?

string.Format("file_{0}_{1:N}.xml", DateTime.Now.Ticks, Guid.NewGuid()) 

By keeping the ticks as part of the name, the names will still be in approximate date order if ordering is important.

The {1:N} gets rid of the curly braces and dashes in the guid.

Also, consider using DateTime.UtcNow.Ticks, so as to guarantee incremental ticks when daylight saving time kicks in.

Neil Moss
Thanks I was not certain about the uniqueness of the Guid across thread. I thought they were salted with the current time, which wouldn't help across threads
Stephane
You are correct - the timestamp is a major component of the Guid, but the algorithm also maintains its own unique counter to handle "simultaneous" requests. A straightforward breakdown of the algorithm is here: http://blogs.msdn.com/b/oldnewthing/archive/2008/06/27/8659071.aspx
Neil Moss
+1  A: 

Depending on your needs you can try:

System.IO.Path.GetTempFileName();

This creates a uniquely named temporary file in the %temp% directory. I suppose you can copy the file to your target location before or after writing to it.

That only guarantees the filename is unique in the temp directory - not at the OP's target location.
Phil
A: 

Guid.NewGuid().ToString() ?

Thomas
A: 

To actually reserve the filename you will have to create the file immediately and check for exceptions.

Another option would be to include a Guid value in your filename.

0xA3