1

我对 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的末尾. 那么我应该在这里使用该语句吗?usingTcpClientusing

4

5 回答 5

2

不要在此处使用 using,因为它会使您的程序由于过早处理而无法运行。只需确保您TcpClient正确地将其移交给新线程并确保线程最终将其处理掉。

我认为最好TcpClient在子线程中创建,以便您可以using在那里使用。

于 2013-07-19T13:34:16.773 回答
2

我认为在这种情况下避免使用 using 块是正确的,因为 using 会导致 using 块末尾的隐式 close() 。我认为这是一个相当常见的恶化来源,因为关于何时使用块的通常建议是“只要对象暗示 IDisposable”。

这是一篇关于何时不使用 using 的权威文章,无论 IDisposable 的实现如何。http://msdn.microsoft.com/en-us/library/aa355056.aspx

于 2013-07-19T13:42:45.590 回答
1

The general rule of thumb is that if its IDisposable then you should dispose of that object.

A using block gives you a nice easy way to do that, but since your TCPClient will persist outside of this method, then it cant be used in this case.

If you really wanted to write nice code then should; declare your TCPClient within your class, have your class implement IDisposable, dispose of your TCPClient within your new Dispose method. (and maybe do something about ending your thread).

That way you can wrap your class within using block.

于 2013-07-19T14:03:24.977 回答
0

我认为有一个不同类型的问题。您必须在 CommunicationListener 中实现 IDisposable 并在那里实例化 TcpClient 并在 CommunicationListener.Dispose 实现中处置 TcpClient。

什么时候最好配置 CommunicationListener?这取决于。

于 2013-07-19T13:35:19.813 回答
0

我会让这个方法所在的类和 CommunicationListener 都是一次性的。然后我将实现一种方法来取消通信侦听器的线程,方法是在其上设置一个标志,这样当您自己的类被释放时,它不会让另一个线程运行。然后在父类的 Dispose 中,设置标志以便 CommunicationListener 可以停止,处理 CommunicationListener,然后在内部处理 TcpClient。

我希望这是有道理的。

于 2013-07-19T13:43:14.440 回答