我正在研究现有的应用程序.此应用程序从大文件中读取数据,然后在进行一些计算后,将数据存储在另一个表中.
但这样做的循环(见下文)需要很长时间.由于文件有时包含1,000条记录,因此整个过程需要数天.
我可以foreach用其他东西替换这个循环吗?我尝试过使用Parallel.ForEach它确实有所帮助.我是新手,所以非常感谢你的帮助.
foreach (record someredord Somereport.r)
{
try
{
using (var command = new SqlCommand("[procname]", sqlConn))
{
command.CommandTimeout = 0;
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(…);
IAsyncResult result = command.BeginExecuteReader();
while (!result.IsCompleted)
{
System.Threading.Thread.Sleep(10);
}
command.EndExecuteReader(result);
}
}
catch (Exception e)
{
…
}
}
Run Code Online (Sandbox Code Playgroud)
在查看答案后,我删除了Async并使用了编辑后的代码.但这并没有提高性能.
using (command = new SqlCommand("[sp]", sqlConn))
{
command.CommandTimeout = 0;
command.CommandType = CommandType.StoredProcedure;
foreach (record someRecord in someReport.)
{
command.Parameters.Clear();
command.Parameters.Add(....)
command.Prepare();
using (dr = command.ExecuteReader())
{
while (dr.Read())
{
if ()
{
}
else if ()
{
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
不是多次循环sql连接,而是考虑从sql server中提取整个数据集并通过数据集处理数据?
编辑:决定进一步解释我的意思..你可以做以下,伪代码如下
第1步:抛弃异步尝试.它没有正确实现,你无论如何都要阻止.所以只需执行该过程,看看是否有帮助.
步骤2:将SqlCommand移动到循环之外,并在每次迭代时重复使用它.这样你就不会为循环中的每个项目产生和销毁它的成本.
警告:确保重置/清除/删除上一次迭代中不需要的参数.我们使用可选参数执行了类似的操作,并且在上一次迭代中使用了'bleed-thru',因为我们没有清理我们不需要的参数!