【发布时间】: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