[英]Using Block with Threading
我对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
实现了接口IDisposable
,因此应该封装在using语句中,但是,在这种情况下,将启动一个使用TcpClient
的新线程,因此using
块的结尾将在TcpClient
已完成使用。 那我应该在这里使用using
语句吗?
不要在这里使用using,因为它会由于早期处理而使您的程序无法正常工作。 只需确保将TcpClient
正确传递给新线程,并确保该线程最终对其进行处理即可。
我认为这将是最好创建TcpClient
在子线程,这样就可以使用using
那里。
我认为您在这种情况下应该避免使用using块,因为在using块的末尾使用隐式close()的结果。 我认为这是一个比较常见的恶化原因,因为有关何时使用块的通常建议是“只要对象隐含IDisposable”。
这是有关何时不使用use的权威文章,无论IDisposable的实现如何。 http://msdn.microsoft.com/zh-CN/library/aa355056.aspx 。
一般的经验法则是,如果其IDisposposable,则应处置该对象。
using块为您提供了一种很好的简便方法,但是由于TCPClient将在该方法之外持久存在,因此在这种情况下无法使用它。
如果您真的想编写漂亮的代码,那么应该; 在您的类中声明您的TCPClient,让您的类实现IDisposable,在新的Dispose方法中处置您的TCPClient。 (也许可以做一些有关结束线程的事情)。
这样,您可以将类包装在using块中。
我认为这是另一种问题。 您必须在CommunicationListener中实现IDisposable,并在那里也实例化TcpClient,并在CommunicationListener.Dispose实现中部署TcpClient。
什么时候最好配置CommunicationListener? 这取决于。
我将使该方法所在的类和CommunicationListener都成为一次性的。 然后,我将通过在其上设置一个标记来实现一种取消通信侦听器线程的方法,以便在处理您自己的类时,它不会使其他线程运行。 然后,在“处置父类”中,设置标志,以便CommunicationListener可以停止,处置CommunicationListener,然后再在内部处置TcpClient。
我希望这是有道理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.