SqlBulkCopy操作挂起而没有响应

时间:2013-12-21 07:49:48

标签: c# sql database visual-studio sqlbulkcopy

我正在使用SqlBulkCopy将几个表复制到数据库。但是,除了一个包含6000 ++数据行的表外,大多数表都已成功复制到数据库。当我运行该功能时,它只是挂在那里而没有响应。

以下是我的代码:

using (SqlConnection destinationConnection = Login.GetConnection())
{
    destinationConnection.Open();
    using (SqlTransaction transaction = destinationConnection.BeginTransaction(IsolationLevel.ReadCommited))
    {
        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection, SqlBulkCopyOptions.KeepIdentity, transaction))
        {
            bulkCopy.DestinationTableName = "dbo." + tableName;
            try
            {
                bulkCopy.WriteToServer(dt);
                transaction.Commit();
                bulkCopySuccess = true;
            }
            catch (Exception ex)
            {
                transaction.Rollback();
                MessageBox.Show(ex.Message, ex.GetType().ToString());
                bulkCopySuccess = false;
            }
        }
    }
}

可能出现的问题是什么?我的代码有问题吗?

1 个答案:

答案 0 :(得分:1)

问题:如果您从主线程运行BulkCopy代码,它将等待/不响应,直到整个操作完成为止。

因此,如果用户想要对UI执行某些操作,那么它将完全无响应并挂起。

解决方案:您可以使用BackgroundWorker组件在后台执行操作,而不会挂起UI

试试这个:

  private void button1_Click(object sender, EventArgs e)
    {
        BackgroundWorker backgroundWorker = new BackgroundWorker();
        backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
        backgroundWorker.RunWorkerAsync();
    }

  private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        DoBulkCopy();
    }

  private void DoBulkCopy()
  {
     using (SqlConnection destinationConnection = Login.GetConnection())
     {
        destinationConnection.Open();
        using (SqlTransaction transaction = destinationConnection.BeginTransaction(IsolationLevel.ReadCommited))
        {
          using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection, SqlBulkCopyOptions.KeepIdentity, transaction))
           {
             bulkCopy.DestinationTableName = "dbo." + tableName;                            
             try
             {
               bulkCopy.WriteToServer(dt);
               transaction.Commit();
               bulkCopySuccess = true;
             }
             catch (Exception ex)
             {
              transaction.Rollback();
              MessageBox.Show(ex.Message, ex.GetType().ToString());
              bulkCopySuccess = false;
             }
            }
         }
      }
}