我正在使用任务将多个文件上传到 sftp 服务器。但目前发生的情况是,当多个任务并行执行时,会生成相同的“fileName”。我想确保每次都会生成不同的文件名。
//Simplified version of my code:
processingTasks = 1000;
while (processingTasks > 0)
{
processingTasks --;
Task<string> task = Task<string>.Factory.StartNew(() =>
{
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
return UploadFileToSFTP(fileName, fileContent);
});
}
以下内容对我有用吗,给我不同的日期时间文件名,或者有更好的方法吗?
processingTasks = 1000;
while (processingTasks > 0)
{
processingTasks --;
Task<string> task = Task<string>.Factory.StartNew(() =>
{
lock(file) //Will only one task go inside this at a time?
{
Thread.Sleep(1000);
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt";
}
return UploadFileToSFTP(fileName, fileContent);
});
}
最佳答案
您可以使用 Emile 的想法来生成“唯一时间戳”:如果尚未返回此时间,则返回 DateTime.Now
,否则返回 future 的第一个空闲秒。
这样,您将得到一个有少量错误的时间戳(或者如果您长时间每秒多次调用此方法,则有很大的错误),但这意味着您不必等待,这对我来说很脆弱。
在代码中:
public static class UniqueTimestamp
{
private static readonly object Lock = new object();
private static DateTime LastTimestamp = DateTime.MinValue;
private static DateTime RoundToSecond(DateTime dt)
{
return new DateTime(dt.Year, dt.Month, dt.Day,
dt.Hour, dt.Minute, dt.Second);
}
public static DateTime GetTimestamp()
{
var now = RoundToSecond(DateTime.Now);
DateTime timestamp;
lock (Lock)
{
if (now > LastTimestamp)
timestamp = now;
else
timestamp = LastTimestamp.AddSeconds(1);
LastTimestamp = timestamp;
}
return timestamp;
}
}
关于.net - 使用 Datetime.Now 具有不同文件名的 TPL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13945981/