【问题标题】:Parallel method execution with lock .NET C#带锁的并行方法执行 .NET C#
【发布时间】:2018-09-22 08:55:38
【问题描述】:

我有一个 xml 文件,其中包含所有带有 IP 地址的学校名称,我正在尝试按计时器间隔备份每所学校(即SchoolFunctions.Backup)。

问题是在某些情况下备份速度太慢,并且在之前的备份仍在运行时会再次启动备份方法......

如果SchoolFunctions.Backup 仍在为那所学校运行,我该如何阻止它被执行?

using (DataTable schools = new DataTable { TableName = "Schools" })
{
     schools.ReadXml(AppSettings.Default.SettingsPath);
     try
     {
         Parallel.ForEach(schools.AsEnumerable(), _opts, row =>
         {
             SchoolFunctions.Backup(row.Field<string>("IPAddress"), row.Field<string>("Name"));
         }
     }

      ...

  }

【问题讨论】:

    标签: c# multithreading parallel-processing


    【解决方案1】:

    我个人会选择凯文斯的回答

    但是,如果您希望这些备份独立工作(不必等待所有学校都完成),并且主要使用您当前的模式。然后可以玩一些这样的想法

    private ConcurrentDictionary<string,bool> _dict = new ConcurrentDictionary<string,bool>();
    
    ...
    
    using (DataTable schools = new DataTable { TableName = "Schools" })
    {
       schools.ReadXml(AppSettings.Default.SettingsPath);
    
       try
       {
          Parallel.ForEach(schools.AsEnumerable(), _opts, row =>
          {
             var ipAddress = row.Field<string>("IPAddress");
    
             // check if there is an ip registered and if its processing
             if (_dict.TryGetValue(ipAddress, out processing) && processing)
                return;
    
              // its not processing ,so update it
             _dict.AddOrUpdate(ipAddress, true, (s, b) => true);
    
             SchoolFunctions.Backup(ipAddress , row.Field<string>("Name"));
    
             // when we are done update processing to false
             _dict.AddOrUpdate(ipAddress, false, (s, b) => false);
    
          }
       }
    }
    

    注意,有很多方法可以做到这一点,但这看起来很有希望。也没有测试过

    另外,您可能只使用 TryAddTryRemove 并忽略该值

    if (!_dict.TryAdd(ipAddress, false))
       return;
    
    SchoolFunctions.Backup(ipAddress , row.Field<string>("Name"));
    
    _dict.TryRemove(ipAddress,out _);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多