Abort SqlRowsCopiedEventArgs

时间:2017-08-03 12:31:44

标签: c#

我正在尝试中止bulkCopy.WriteToServer(reader); 在文档中,我发现了SqlRowsCopiedEventArgs.Abort属性,它似乎正在做我需要的东西。但我不明白如何使用它,我找不到它的例子。

https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlrowscopiedeventargs.abort.aspx

我会非常感谢SqlRowsCopiedEventArgs.Abort属性如何用于停止bulkCopy的工作示例。

我的代码:

  using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connDetails.ConnString)) {
                    bulkCopy.NotifyAfter = 1;
                    bulkCopy.SqlRowsCopied += (sender1, e1) =>
                    {
                        if (tryAbort == true)
                        {
                            Log.Info(" e1.Abort = true"); //this line never happens
                            e1.Abort = true;

                        }

                    };
                    bulkCopy.BatchSize =(int)(batchSize != null ? batchSize : (int)ConfigSettings.CSettings.SqlServerDefaultBatchSize);
                         bulkCopy.BulkCopyTimeout = 0;
                         Log.Info("BatchSize:" + bulkCopy.BatchSize.ToString());
                         bulkCopy.DestinationTableName = destinationTable;
                         while (reader.Read()) {
                             try
                             {
                                 bulkCopy.WriteToServer(reader);
                                 //bulkCopy.SqlRowsCopied
                             }
                             catch (Exception ex)
                             {
                                 Log.Info("Caught " + ex.GetType() + " while calling bulkCopy.WriteToServer(reader);");
                                 Log.Info("No records were added to destination");
                             }
                         }

当用户尝试中止此函数时调用:

        public void sourceAbort()
    {
        tryAbort = true;
        conn.Dispose();

    }

1 个答案:

答案 0 :(得分:0)

很抱歉,如果答案很晚,但这是一个高级示例:

 using (var bulkCopy = new SqlBulkCopy(connStr))
{
     bulkCopy.NotifyAfter = x; // after how many rows of copy do you want a notif event
     bulkCopy.SqlRowsCopied += (sender, eventArgs) =>
                               {
                                 if (someLogic) // some condition to abort                                          {      
                                         eventArgs.Abort = true;
                                        }                                        
                                };                                           
}

在x行复制

之后调用SqlRowsCopied