Is the Dispose method used inside a function?

so lately I have been working with a one-time object, and I was wondering if it would be useful to use the object inside a function? as between these two functions, using .Dispose () really matters inside the function, since all objects inside the function disappear as soon as it ends

void FOO()
{
    var x= new DisposableObject();
    //stuff
}

void FOO()
{
    using(var x= new DisposableObject())
    {
        //stuff
    }
}
+4
source share
4 answers

All objects inside the function disappear as soon as it ends

Objects will remain, local links will disappear. Objects will “disappear” when the garbage collector starts up and determines that they are inaccessible.

, ( ), .

, . , GC , .

Dispose, .

, : 1, 2.

+2

Dispose() , . , , . Dispose() ( using, ) , , .

+6

.

GC , . , GC , , .

, , .

, , , . , .

+2

Set a breakpoint in the Dispose () method and run these tests using debugging. TestMethod1 does not hit the breakpoint during TestMethod2.

As others have noted, this is related to how GC.Net works. If you are going to implement the IDiisposeable interface, you probably want to put your class in a using statement or call .Dispose () so that you have more predictable application behavior.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject2
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            var disposable = new DisposableObject();
            disposable.DoSomething();
        }

        [TestMethod]
        public void TestMethod2()
        {
            using (var disposable = new DisposableObject())
            {
                disposable.DoSomething();
            }
        }
    }

    public class DisposableObject : IDisposable
    {
        public void Dispose()
        {
            // dispose here
        }

        public void DoSomething()
        {
            // do something here
        }
    }
}
+1
source

Source: https://habr.com/ru/post/1614800/


All Articles