GC是否收集引用套接字的对象?

时间:2019-03-12 16:03:51

标签: c# sockets asynchronous garbage-collection circular-reference

GC是否会收集OBS对象obs

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            CreateSOB();
            Form form = new Form();
            form.Show();
            GC.Collect();
            Application.Run();
        }

        static void CreateSOB()
        {
            SOB sop = new SOB();
        }

        public class SOB
        {
            private Socket socket;

            public SOB()
            {
                socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP);
                socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
                byte[] buffer = new byte[4096];
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), buffer);
            }

            public void ReceiveCallback(IAsyncResult ar)
            {
                MessageBox.Show("recv:" + socket.EndReceive(ar).ToString());
                byte[] buffer = new byte[4096];
                socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), buffer);
            }
        }
    }
}

在上面的示例中,CreateSOB()创建了类型为sob的局部变量SOB,该变量又创建了一个套接字并保留对其的引用。

由于没有线程直接引用对象sob,GC会收集它吗?

0 个答案:

没有答案