Skip to main content
 首页 » 编程设计

c#之使用 Parallel.Foreach 的数据表中的索引超出范围异常

2024年02月06日14shihaiming

我正在尝试使用反向 DNS 映射来扩充一个在一列中具有 IP 地址的数据表。我从其他地方得到这个数据表。然后我使用 SQLBulkcopy 将该表导出到 SQL Server

我添加了两列,一列用于 dns 名称,一列仅用于顶级域部分。因为我有很多 IP,并且做反向 DNS 需要一些时间,所以我为每个 IP 使用了一个 Parallel。 奇怪的是,我在并行循环的 NestedException 中得到了奇怪的不可预测的 IndexOutOfRangeExceptions(或者有时在数据表中调用 clear 时在并行循环之外)。为什么?

这是我在做的事情

        //mapping specifies a mapping within the DataTable and the Database 
 
        SqlBulkCopy copy = new SqlBulkCopy(cn); 
        foreach (KeyValuePair<int, int> pair in mapping) 
        {                                                                        
            copy.ColumnMappings.Add(pair.Key, pair.Value); 
        } 
 
 
        dt.Columns.Add("URL"); 
        dt.Columns.Add("Domain"); 
        solver.AddDNSInfo(dt, 1); //second row has the IP 
        copy.WriteToServer(dt); 
        dt.Clear();     //exceptions are thrown here    
 
 
 
 
    //ipIndex is the index within the datatable where the IP of interest is.  
    //In my scenario ipIndex=1 
    public void AddDNSInfo(DataTable table, int ipIndex) 
    { 
        Parallel.ForEach(table.AsEnumerable(), row => 
        { 
                string URL = GetDNSName((string)row[ipIndex]); 
                row["URL"] = URL; //exceptions are thrown here 
                row["Domain"] = GetTopLevelDomain(URL); 
                Console.Write("*"); 
        }); 

请您参考如下方法:

因为DataTable对于多线程写操作不是线程安全的。

MSDN says:

This type is safe for multithreaded read operations. You must synchronize any write operations.

当您在 Parallel.ForEach 中同时编写具有多个线程的新列时,您执行以下操作:

  row["URL"] = URL; 
  row["Domain"] = GetTopLevelDomain(URL); 

您需要将任何写入调用同步到您的DataTable(使用锁或某种形式的监视器)