Memory leak on BeginInvoke

1) I heard that when we do not call EndInvoke (), it can lead to a memory leak? can you demonstrate this, how can this lead to a memory leak?

2) When I intend to call EndInvoke (), should I use the code as shown below?

namespace BlockMechanism
{
    public delegate int MyDelegate(List<int> someInts);
    class MainClass
    {
        static void Main()
        {
           List<int> someInts = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
           MyDelegate test = FinalResult;
           IAsyncResult res=test.BeginInvoke(someInts, null, test);
           Console.WriteLine(test.EndInvoke(res));
           Console.ReadKey(true);
        }

        public static int FinalResult(List<int> Mylist)
        {
            return Mylist.Sum();
        }

    }
}
+3
source share
2 answers

, , EndInvoke , . , Invoke FinalResult. EndInvoke , BeginInvoke:

class Program
{
    public delegate int MyDelegate(List<int> someInts);
    class MainClass
    {
        static void Main()
        {
            List<int> someInts = new List<int> { 1, 2, 3, 4, 5, 6, 7 };
            MyDelegate test = FinalResult;
            test.BeginInvoke(someInts, ar => 
            {
                MyDelegate del = (MyDelegate)ar.AsyncState;
                Console.WriteLine(del.EndInvoke(ar));
            }, test);
            Console.ReadKey(true);
        }

        public static int FinalResult(List<int> Mylist)
        {
            return Mylist.Sum();
        }
    }
}

, thread.

PS: List <t> , .

+4

MSDN Begin/EndInvoke()

, EndInvoke(), -. , , -.

BeginInvoke() EndInvoke() .

:

  • , EndInvoke .

  • WaitHandle, System.IAsyncResult.AsyncWaitHandle, WaitOne , WaitHandle, EndInvoke.

  • IAsyncResult, BeginInvoke, , , EndInvoke.

  • BeginInvoke. ThreadPool, . EndInvoke.

+2

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


All Articles