[英]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);
}
}
}
This method is used for listening. 此方法用于收听。
If I use thread to create this method 如果我使用线程创建此方法
myThread = new Thread(new ThreadStart(BeginListen));
myThread.IsBackground = true;
myThread.Start();
Will it be collected by GC when catching an exception? 捕获异常时,GC会收集它吗? Or do I need to add
GC.Collect();
还是我需要添加
GC.Collect();
manually in the catch? 手动抓?
What do you want to be collected? 您想收集什么? Well, generally you shouldn't call GC.Collect yourself.
好吧,通常你不应该打电话给GC。
I would leave it for the GC to collect the objects and reclaim memory resources. 我将其留给GC收集对象并回收内存资源。 But when something implements IDisposable, you generally should use the
using
statement. 但是,当某些实现IDisposable时,通常应使用
using
语句。
In the example provided, maybe you don't need to use a using
statement, because the socket may be used later, also, maybe there is already some code to dispose the object inside your ConnectionClient
class. 在提供的示例中,也许您不需要使用
using
语句,因为套接字可能在以后使用,而且,也许已经有一些代码可以将对象放置在ConnectionClient
类中。 Disposing it now could cause you problems. 现在处理它可能会给您带来麻烦。
But generally you can use the using
statement to automatically handle the disposal of resources, eg opening file streams, creating memory streams, and so on. 但是通常,您可以使用
using
语句自动处理资源的处置,例如打开文件流,创建内存流等。
To learn more about what the using statement does, Click here. 要了解有关using语句的更多信息,请单击此处。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.