C# 使用语句后的生活
使用语句后字段是否等于nullC# 使用语句后的生活,c#,.net,entity-framework,using-statement,C#,.net,Entity Framework,Using Statement,使用语句后字段是否等于null class Program { MyDBContext context; public void Start() { Run1(); Run2(); ... } void Run1() { using (context = new MyDBContext()) { //...some context machina
class Program
{
MyDBContext context;
public void Start()
{
Run1();
Run2();
...
}
void Run1()
{
using (context = new MyDBContext())
{
//...some context machination
}
}
void Run2()
{
if(context != null)
{
//?? GC not collect context (memory leak)
}
}
}
在我的应用程序中,我有内存泄漏。使用实体框架的类中存在漏洞。可能上下文不是由GC收集的,可能是由他将许多机密信息存储在其他地方。
使用
不会使您的上下文
为空--它只会对其调用Dispose()
方法
您不应将上下文定义为私有字段,而应将其定义为局部变量:
class Program
{
// MyDBContext context;
public void Start()
{
Run1();
Run2();
...
}
void Run1()
{
using (var context = new MyDBContext())
{
//...some context machination
}
}
void Run2()
{
using (var context = new MyDBContext())
{
// ...
}
}
}
使用
不会使您的上下文
为空——它只会对其调用Dispose()
方法
您不应将上下文定义为私有字段,而应将其定义为局部变量:
class Program
{
// MyDBContext context;
public void Start()
{
Run1();
Run2();
...
}
void Run1()
{
using (var context = new MyDBContext())
{
//...some context machination
}
}
void Run2()
{
using (var context = new MyDBContext())
{
// ...
}
}
}
在using块的末尾,将调用MyDBContext.Dispose
方法,释放所有非托管资源(假设该方法已正确实现),但该字段不会设置为no null
不将其设置为null不应该是内存泄漏的原因。问题在别处。在using块的末尾,将调用MyDBContext.Dispose
方法,释放所有非托管资源(假设该方法已正确实现),但该字段不会设置为no null
不将其设置为null不应该是内存泄漏的原因。问题在别处。使用语句的只会自动运行IDisposable
对象的context.Dispose()
方法。因此,除非您显式地将对象设置为null,否则在使用
语句后,对象将不会为null
此外,MyDBContext的创建者需要在Dispose()
方法中正确处理内部清理,否则您可能仍然存在内存问题(尤其是对于非托管对象)。using
语句只会自动运行IDisposable
对象的context.Dispose()
方法。因此,除非您显式地将对象设置为null,否则在使用
语句后,对象将不会为null
此外,MyDBContext的创建者需要在Dispose()
方法中正确处理内部清理,否则您可能仍然存在内存问题(特别是对于非托管对象)