我使用 SQL Server 2008 Express 数据库在标准 C# Windows 窗体应用程序中编写了自定义复制函数。它基本上提取了一组需要针对订阅者数据库执行的 sql 语句。在完全刷新时,这最多可以运行 200k+ 需要执行的语句。
我在代码块中处理这些语句,如下所示:
using (SqlConnection connection = ConnectionManager.GetConnection())
{
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
// Process 200k+ Insert/Update/Delete statements using SqlCommands
transaction.Commit
}
我发现,对于前 30k 条语句,我的应用程序内存使用量保持在 40mb 左右相当稳定。之后它似乎突然跳到 300mb 左右然后增长,直到我遇到 OutOfMemory 异常。
我正在使用的方法是否可行,我可以在单个事务中处理那么多语句吗?我想我应该能够做到这一点。如果有更好的方法,我很乐意在这里。我需要它是事务性的,否则部分复制会导致数据库损坏。
谢谢。
编辑:
重新启动计算机后,我成功完成了 200k+ 的完整复制。尽管在复制完成后内存使用量一度增长到 1.4Gb,但内存使用量一路下降到 40mb。这让我得出结论,我的循环中处理命令的某些东西可能导致内存增长。
最佳答案
您是否在关闭前处理
您的表单和一次性控件?
Wrap all Disposable objects in Using Statement. Click here for more details
Don't open/close the Connection over and over again, instead send the data to database in single Transaction. Click here for more details
Still your application is holding tooo much memory then you need a Doctor like Red Gate Ants Memory Profiler. Click here to see more details about it
can I process that many statements inside a single transaction?
您有以下选项可以执行此操作...
- 在
Stored Proc
中批量插入和操作记录。 - 准备
XML
并将字符串发送到Database
。 - 通过Stored Proc发送Sql Server中的Read only
DataTable
示例存储过程
Begin Try
Set NoCount ON
Set XACT_Abort ON
Begin TRan
--Your queries
Commit Tran
Begin Tran
Begin Catch
Rollback Tran
End Catch
确保对象在不使用时Dispose
。
应该是这样的
using (SqlConnection connection = new SqlConnection())
{
connection.Open();
using (SqlTransaction transaction = connection.BeginTransaction())
{
transaction.Commit();
}
}
您是否也验证了 SqlCommand
?
using (SqlCommand cmd = new SqlCommand())
{
}
关于c# - 使用 SqlTransaction 处理数千条 SqlCommand 导致内存异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675430/