1

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();
    }
4

1 回答 1

6

代码分析警告是因为您在一次性对象上使用了对象初始化程序。

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

如果单独设置属性

_webSocketServer = new WebSocketServer(port, IPAddress.Any);
_webSocketServer.OnReceive = OnReceive;

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

于 2014-02-02T10:31:59.183 回答