在多线程应用程序中获取唯一的文件名
我需要在多线程应用程序中构建一个唯一的文件名,该应用程序正在序列化磁盘上的一些数据。 我可以使用什么方法来确保名称的唯一性。 该应用程序之前不是多线程的,并且使用的是 Ticks。当使用多线程时,它失败的速度比我预期的要快得多。 我现在将 CurrentThreadId 添加到文件名中,应该可以做到这一点
string.Format("file_{0}_{1}.xml", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId)
是否有任何“更智能”的方法可以做到这一点?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用 Guid.NewGuid() 而不是线程 id 怎么样?
通过将勾号保留为名称的一部分,如果排序很重要,名称仍将按大致日期顺序排列。
{1:N} 去掉了 GUI 中的花括号和破折号。
另外,请考虑使用 DateTime.UtcNow.Ticks,以便保证在夏令时开始时增量刻度。
What about Guid.NewGuid() instead of the thread id?
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.
根据您的需要,您可以尝试:
System.IO.Path.GetTempFileName();
这会在 %temp% 目录中创建一个唯一命名的临时文件。我想您可以在写入文件之前或之后将文件复制到目标位置。
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.
要实际保留文件名,您必须立即创建文件并检查是否有异常。
另一种选择是在文件名中包含 Guid 值。
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.
怎么样
How about