问题
I am currently developing some desktop applications using websockets (to be more precisely: i am working with Alchemy WebSockets). By now my code is working fine, but Visual Studio 2010 tells me to
Warning 2 CA2000 : Microsoft.Reliability : In method 'ServerController.SetupServer(int)', call System.IDisposable.Dispose on object '<>g__initLocal0' before all references to it are out of scope. C:\Users\MaRiedl\documents\visual studio 2010\Projects\Alchemy-WebSockets\AWS-Server\ServerController.cs 38 AWS-Server
I already tried to fix this problem with MSDNs help (http://msdn.microsoft.com/en-us/library/ms182289.aspx) and (of course) by searching stackoverflow.com day and night (Uses of "using" in C#) - but sadly it won't get any better.
So here's my question: am I far to "junior" to see the problem I can't find, or is this just a false positive from Visual Studio 2010?
Here's the piece of code I am struggling with:
private WebSocketServer _webSocketServer;
private void SetupServer(int port)
{
// set port and configure authorized ip addresses to connect to the server
_webSocketServer = new WebSocketServer(port, IPAddress.Any)
{
OnReceive = OnReceive,
OnSend = OnSend,
OnConnect = OnConnect,
OnConnected = OnConnected,
OnDisconnect = OnDisconnect,
TimeOut = new TimeSpan(0, TimeoutInMinutes, 0)
};
_webSocketServer.Start();
}
回答1:
The Code Analysis warning is because you are using an object initializer on a disposable object.
Whenever you use an object initializer a temporary, invisible local is created (see this question for more details). It is this object (<>g__initLocal0
) that the message is referring to, as you are not able to dispose of it if an exception is thrown while it is being created.
If you set the properties separately
_webSocketServer = new WebSocketServer(port, IPAddress.Any);
_webSocketServer.OnReceive = OnReceive;
then the message will go away, as no temporary object is created.
来源:https://stackoverflow.com/questions/21380279/ca2000-out-of-school-junior-programmers-mistakes-or-false-positive