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会收集它吗?