c# 如果捕获一个新方法的异常,GC 会收集这个对象吗?

c# if catch exception of a new method, will GC collects this object?

private void BeginListen()
{
    while (isWatch)
    {
        try
        {

            Socket newSocket = socket.Accept();
            ConnectionClient conn = new ConnectionClient(newSocket, ShowMsg, RemoveClientConnection, SendMsgToController);
            string strRemoteEndPoint = newSocket.RemoteEndPoint.ToString();
            if (dictConn.ContainsKey(strRemoteEndPoint.Substring(0, strRemoteEndPoint.LastIndexOf(":"))))
                dictConn[strRemoteEndPoint.Substring(0, strRemoteEndPoint.LastIndexOf(":"))].isRec = true;
            else
                dictConn.Add(strRemoteEndPoint.Substring(0, strRemoteEndPoint.LastIndexOf(":")), conn);
            UpdateControllerStatus(strRemoteEndPoint, " online");
        }
        catch (Exception ex)
        {
            ExceptionLog(ex);
        }
    }
}

此方法用于收听

如果我使用线程来创建这个方法

myThread = new Thread(new ThreadStart(BeginListen));
myThread.IsBackground = true;
myThread.Start();

捕获异常时会被GC回收吗? 或者我需要在 catch 中手动添加 GC.Collect(); 吗?

你想收集什么?嗯,通常你不应该自己打电话给 GC.Collect。

我会留给 GC 来收集对象和回收内存资源。但是当某些东西实现了 IDisposable 时,您通常应该使用 using 语句。

在提供的示例中,也许您不需要使用 using 语句,因为稍后可能会使用套接字,另外,也许已经有一些代码可以在您的 ConnectionClient class。现在处理它可能会给您带来麻烦。

但一般可以使用using语句来自动处理资源的处置,例如打开文件流,创建内存流等。

要详细了解 using 语句的作用,Click here.