如何在使用后强制对象处理以释放内存?而且,你如何强制GC收集?
这是我的保存代码。我注意到,每次执行此函数时,我的内存消耗都会上升,最终会在几次点击后导致内存不足错误。
protected void btnSaveEmptyOC_Click(object sender, EventArgs e)
{
try
{
if (ViewState["ServiceDetailID"].ToString() != null)
{
CashExpense tblCashExpenses = new CashExpense();
Guid CashExpensesID = Guid.NewGuid();
tblCashExpenses.CashExpensesID = CashExpensesID;
tblCashExpenses.ServiceDetailsID = new Guid(ViewState["ServiceDetailID"].ToString());
tblCashExpenses.Description = txtDescriptionEmptyOC.Text;
tblCashExpenses.Quantity = Decimal.Parse(txtQTYEmptyOC.Text);
tblCashExpenses.UnitCost = Decimal.Parse(txtUnitCostEmptyOC.Text);
tblCashExpenses.CreatedBy = User.Identity.Name;
tblCashExpenses.DateCreated = DateTime.Now;
tblCashExpenses.CashExpensesTypeID = "OTHER";
CashExpenses_worker.insert(tblCashExpenses);
CashExpenses_worker.submit();
//Clear items after saving
txtDescriptionEmptyOC.Text = "";
txtQTYEmptyOC.Text = "";
txtUnitCostEmptyOC.Text = "";
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOC2, "SaveEmptyOC", this.Page);
MyAuditProvider.Insert(this.GetType().ToString(), ViewState["MarginAnalysisID"].ToString(), MessageCenter.Mode.ADD, MessageCenter.CashExpenseMaintenace.InsertOC2, Page.Request, User);
divOtherCost.Visible = false;
grd_othercost.Visible = true;
btnaddothercost.Visible = true;
tblCashExpenses = null;
}
else
{
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.SaveServiceDetailOC, "SaveEmptyOC", this.Page);
}
}
catch
{
ValidationMessage.ShowValidationMessage(MessageCenter.CashExpenseMaintenace.InsertOCError, "SaveEmptyOC", this.Page);
}
finally
{
//Rebinds the Grid
populategrd_othercost();
Dispose();
GC.SuppressFinalize(this);
}
}
这是我的业务层类
public class CashExpensesBL
{
CEADataStoreDataContext CashExpensesDB = new CEADataStoreDataContext();
public IEnumerable<CashExpense> get()
{
return CashExpensesDB.CashExpenses;
}
public IEnumerable<CashExpense> get(Expression<Func<CashExpense, Boolean>> express)
{
return CashExpensesDB.CashExpenses.Where(express);
}
public void insert(CashExpense item)
{
CashExpensesDB.CashExpenses.InsertOnSubmit(item);
}
public void delete(CashExpense item)
{
CashExpensesDB.CashExpenses.DeleteOnSubmit(item);
}
public void deleteDC(Guid servicedetailid)
{
CashExpensesDB.sp_deleteDefaultCost(servicedetailid);
}
public void submit()
{
CashExpensesDB.SubmitChanges();
}
}
答案 0 :(得分:4)
您应该处置DataContext
。我无法看到它被移除到任何地方,因此连接将保持打开状态并且可以保持引用(阻止GC将其拾取)。这可能是导致问题的原因。如果您不想手动处理,则可以在using
块内执行事务。
编辑以响应业务层更新 -
您可以将方法包装在using
块中,如下所示:
public void insert(CashExpense item)
{
using(CEADataStoreDataContext CashExpensesDB = new CEADataStoreDataContext())
{
CashExpensesDB.CashExpenses.InsertOnSubmit(item);
CashExpensesDB.SubmitChanges();
}
}
答案 1 :(得分:4)
将空值分配给引用对象的变量,使用GC.Collect();
强制进行垃圾回收。您可能需要连续两次调用它来加速不可访问的对象。
答案 2 :(得分:0)
将对象设置为null,然后调用:
GC.Collect的(); GC.WaitForPendingFinalizers();