Stéphane
Stéphane

Reputation: 11864

Get unique filename in a multithreaded application

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?

Upvotes: 0

Views: 1265

Answers (4)

Thomas
Thomas

Reputation: 717

How about

Guid.NewGuid().ToString()

Upvotes: 0

Neil Moss
Neil Moss

Reputation: 6818

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.

Upvotes: 9

Dirk Vollmar
Dirk Vollmar

Reputation: 176169

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.

Upvotes: 0

OliK
OliK

Reputation: 265

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.

Upvotes: 1

Related Questions