【问题标题】:BulkCopy.WriteToServerAsync() Not Working Importing RecordsBulkCopy.WriteToServerAsync() 不工作导入记录
【发布时间】:2018-01-30 23:00:57
【问题描述】:

我编写了一个批量导入记录的例程。它不起作用,我认为问题是我在这里没有任何等待,但我不知道如何或在哪里放置它。由于我的项目的性质,我不想要方法成为异步方法。我只是使用异步来通知更新。

    public int LoadTempFile(string fn, string tableName)
    {
        int retVal = 1;
        // loads a CSV file into a temporary file of the same structure
        StatusWindow sw = new StatusWindow("Loading Temp Files");
        sw.Show();

        try
        {
            string cs = GetConnectionString() + ";Asynchronous Processing=true;"; 
            SqlConnection cxs = new SqlConnection(cs);
            SqlCommand cmd = new SqlCommand("Truncate table " + tableName, cxs);
            cxs.Open();
            cmd.ExecuteNonQuery();
            cmd.CommandTimeout = 640;
            cxs.Close();

            using (SqlBulkCopy copy = new SqlBulkCopy(cs))
            {
                using (StreamReader file = new StreamReader(fn))
                {
                    CsvReader csv = new CsvReader(file, true);
                    copy.DestinationTableName = tableName;
                    copy.BulkCopyTimeout = 1640;
                    copy.NotifyAfter = 100;
                    copy.SqlRowsCopied += (sender, eventArgs) =>
                     {
                        sw.Update(eventArgs.RowsCopied.ToString() + " Records Copied");
                    };


                    try
                    {
                       copy.WriteToServerAsync(csv);
                    }
                    catch (SqlException ex)
                    {
                        MessageBox.Show("SQL Error Importing " + fn + Environment.NewLine + ex.Message);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error Importing " + fn + Environment.NewLine + ex.Message);
                    }

                }
            }
        }
        catch (Exception e)
        {
            MessageBox.Show("Error In Temp Files " + fn + Environment.NewLine + e.ToString());
            retVal = 0;
        }
        finally
        { sw.Close(); }
        return (retVal);
    }

如果有任何帮助或意见,我将不胜感激。另外,我的编码风格的 cmets 或类似的东西也是受欢迎的。

【问题讨论】:

  • 那你为什么打电话给WriteToServerAsync而不是WriteToServer
  • 不需要需要调用async方法来获取通知
  • 查看NotifyAfter 属性的文档。它使用事件处理程序和WriteToServer 方法

标签: c# asynchronous sqlbulkcopy


【解决方案1】:

你是对的,这段代码不起作用的原因是你从不等待对copy.WriteToServerAsync(csv);的调用,该方法返回一个Task对象

我不希望该方法成为异步方法。我只是使用异步来通知更新。

获取通知不以使用async 版本的方法为条件。其实微软自己的exampleSqlRowsCopied使用的是同步版本,即copy.WriteToServer(...)

除非您一直使用 async,否则使用 async 将无助于获取 UI 通知。 See this Q&A 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多