.net - 使用 Datetime.Now 具有不同文件名的 TPL

标签 .net datetime concurrency locking task-parallel-library

我正在使用任务将多个文件上传到 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/

相关文章:

c# - 使用 HtmlAgilityPack 下载网页时违反 HTTP 协议(protocol)

c# - 从 Delphi 调用 .NET DLL

c# - 为什么c#不允许将SqlDatetime.MinValue分配给日期时间但允许比较

mysql - 如何在mysql中将日期时间分组为3小时的间隔

java - Actor 模型实现中的多个 Apache HTTP 客户端

python - 依赖于 Python 的并行任务处理并发,例如 GNU Make

c# - 仅在第一次打印时出现 Hardmargin 的奇怪打印问题 (WinForms)

c# - 如何知道代码是否在 TransactionScope 内?

python - 在 Python 中将 N 秒添加到 datetime.time 的标准方法是什么?

java - 如何使多个线程中的一个线程运行最长时间(等待队列中的最短时间)?