CA2000 - "校外初级程序员" - 错误或误报?

Mat*_* R. 1 c# dispose false-positive websocket ca2000

我目前正在使用websockets开发一些桌面应用程序(更准确地说:我正在使用Alchemy WebSockets).到现在为止,我的代码工作正常,但Visual Studio 2010告诉我

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
Run Code Online (Sandbox Code Playgroud)

我已经尝试用MSDN帮助(http://msdn.microsoft.com/en-us/library/ms182289.aspx)和(当然)通过日夜搜索stackoverflow.com 来解决这个问题(使用"使用"在C#) - 但遗憾的是它不会变得更好.

所以这是我的问题:我是否能够"找到"找不到的问题,或者这只是Visual Studio 2010中的误报?

这是我正在努力解决的一段代码:

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();
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*inC 6

代码分析警告是因为您在一次性对象上使用对象初始值设定项.

每当您使用对象初始值设定项时,都会创建一个临时的,不可见的本地(有关详细信息,请参阅此问题).<>g__initLocal0消息所指的是这个对象(),因为如果在创建异常时抛出异常,则无法处置它.

如果单独设置属性

_webSocketServer = new WebSocketServer(port, IPAddress.Any);
_webSocketServer.OnReceive = OnReceive;
Run Code Online (Sandbox Code Playgroud)

然后消息将消失,因为没有创建临时对象.