Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用语句后的生活_C#_.net_Entity Framework_Using Statement - Fatal编程技术网

C# 使用语句后的生活

C# 使用语句后的生活,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

使用语句后字段是否等于null

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()
方法中正确处理内部清理,否则您可能仍然存在内存问题(特别是对于非托管对象)