BulkCopy.WriteToServerAsync() 无法导入记录



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

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);
}

我将不胜感激任何帮助或意见。此外,也欢迎对我的编码风格或类似的东西发表评论。

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

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

获取通知不以使用该方法async版本为条件。事实上,Microsoft自己的SqlRowsCopied示例使用同步版本,即copy.WriteToServer(...).

使用async无助于获取 UI 通知,除非您一直async。有关更多信息,请参阅此问答。

最新更新