我对 C# 相当有经验,但是我以前从未遇到过这个问题,我想知道是否有更有经验的 C# 开发人员知道在这种情况下该怎么做。这是相关方法的代码:(问题在代码块之后解释)
public void ConnectToRemoteServer()
{
Console.WriteLine("Attempting to connect to " + config.GetString(ConfigParams.MasterServerIp) + ":" + config.GetString(ConfigParams.MasterServerPort));
TcpClient client = new TcpClient();
IPEndPoint address = new IPEndPoint(IPAddress.Parse(config.GetString(ConfigParams.MasterServerIp)), config.GetInt(ConfigParams.MasterServerPort));
Console.WriteLine("Connecting...");
//Begin asynchronous sever communication
if (this.autoTask == null)
{
communicator = new CommunicationListener(client, config, address);
}
else
{
communicator = new CommunicationListener(client, config, address, this.autoTask);
}
Thread communicationThread = new Thread(new ThreadStart(communicator.Start));
communicationThread.Start();
}
我想知道的部分是我是否应该在这段代码中使用 using 语句。我知道TcpClient
实现了 interface IDisposable
,因此应该封装在 using 语句中,但是,在这种情况下,会启动一个使用 的新线程,因此在使用完成之前将到达块TcpClient
的末尾. 那么我应该在这里使用该语句吗?using
TcpClient
using