Parallel.ForEach在递归方法中

时间:2013-04-04 15:54:20

标签: c# .net-4.0 task-parallel-library

我有一个收集共享信息并将结果写入数据库的方法, 我使用Parallel.Foreach,这提高了性能,特别是如果扫描100 TB

如果我在我的本地数据库中运行此代码,我没有问题,但在沙盒数据库上我有大量的异常/ innerExceptions

代码:

private static INodeCollection NodesLookUp(string path, int maximumLevel)
       {

           var shareCollectionNode = new ShareCollection(path);
           shareCollectionNode.GetNodeProperties();
           shareCollectionNode.GetPermissionEntires();
           WriteNodeToDatabase(shareCollectionNode); // write collected infomation to database
           if (maximumLevel <= 0 && _maximumSubLevels != -1)
           {
               return shareCollectionNode;
           }

           Parallel.ForEach(Directory.GetDirectories(shareCollectionNode.FullPath), directory =>
           {
              try
             {
                  lock (shareCollectionNode)
                  {
                      shareCollectionNode.AddNode(NodesLookUp(directory, maximumLevel - 1));
                  }

              }
              catch (UnauthorizedAccessException unauthorizedAccessException)
              {
                  lock (_shareIssues)
                  {
                      _shareIssues.Add(new ShareIssue(TraceStatu.UnauthorizedAccess, directory,
                     unauthorizedAccessException.Message, dfsId, currentLevel));
                  }

               }

           });

           return shareCollectionNode;
       }

写入数据库:

private static void WriteNodeToDatabase(ShareCollection shareCollection)
    {
        var nodeId = Persistence.UpsertShare(shareCollection);
        var sharePermissions = new List<IPermissionRight>();
        foreach (var permissionEntry in shareCollection.PermissionEntries)
        {
            permissionEntry.NodeId = nodeId;
            var permissionEntryId = Persistence.InsertPermissionEntry(permissionEntry);
            permissionEntry.SetPermissions(permissionEntryId);
            sharePermissions.AddRange(permissionEntry.Permissions);
        }
        Persistence.InsertPermissions(sharePermissions);
    }

例外:

    System.Data.SqlClient.SqlException (0x80131904): Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
   at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()

如果我删除了Parallel.Foreach并使用normal for循环,那么除了应用程序需要很长时间才能运行之后我没有任何问题。

1 个答案:

答案 0 :(得分:1)

首先尝试替换此

lock (shareCollectionNode)
{
    shareCollectionNode.AddNode(NodesLookUp(directory, maximumLevel - 1));
}

用这个

var node = NodesLookUp(directory, maximumLevel - 1);
lock (shareCollectionNode)
{
    shareCollectionNode.AddNode(node);
}

和第二次锁相同。

虽然这是通过并行实现所需内容的更好方法,但它也可能有助于在本地重现相同的错误,因为它应该增加数据库活动。

我认为实际问题依赖于DataBase事务 - 看起来像在并发数据库操作期间导致表中的中间结果返回无效数据;在我们看到实际的查询和表架构之前,我不能说更多。