CA2000-“校外初级程序员"错误或假阳性? [英] CA2000 - "out-of-school-junior-programmers"-mistakes or false positive?

查看:131
本文介绍了CA2000-“校外初级程序员"错误或假阳性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我已经尝试在MSDN的帮助下解决此问题( http://msdn.microsoft.com/en-us/library/ms182289.aspx )和(当然)是通过日夜搜索stackoverflow.com()-但可悲的是它不会变得更好.

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.

所以这是我的问题:我是不是很初级,看不到我找不到的问题,或者这只是Visual Studio 2010的误报?

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

推荐答案

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

The Code Analysis warning is because you are using an object initializer on a disposable object.

无论何时使用对象初始化程序,都会创建一个不可见的临时局部变量(有关更多详细信息,请参见此问题).消息所引用的是此对象(<>g__initLocal0),因为如果在创建消息时引发异常,则无法处理它.

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.

如果分别设置属性

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

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

then the message will go away, as no temporary object is created.

这篇关于CA2000-“校外初级程序员"错误或假阳性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆