CA1001:在ViewModel

时间:2016-10-20 18:05:11

标签: c# visual-studio backgroundworker code-analysis idisposable

  public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {

                if (processFileBackgroundWorker != null)
                {
                    processFileBackgroundWorker.Dispose();
                    processFileBackgroundWorker = null;
                }
            }
        }

我在视图模型中使用后台工作程序,并且在fxcop中出现CA1001错误。我知道我需要从Idisposable继承,并实现上面的接口。我更好奇这是如何工作的,如果只是在我的课程中任意添加这个代码将完成任何事情。我尝试设置一个断点,这个代码永远不会被调用或使用,我将非常感谢如何正确实现它。

1 个答案:

答案 0 :(得分:1)

If fxcop pounds its spoon on the tray and demands IDisposable, and it's not an option to get rid of fxcop, I guess you're stuck paying your taxes.

It's a bit silly in this particular case, because IDisposable is for disposing unmanaged resources when an object goes out of the scope of a using block or a try/catch, and viewmodels don't go out of scope in that way. So in normal viewmodel usage, nothing calls Dispose().

But you do often discard them before program exit (at program exit, nobody cares if anything gets disposed -- it's all going straight in the dumpster). I would implement IDisposable, make it correctly dispose of the BackgroundWorker as you're doing, and if there is a point in your code where an instance of that viewmodel is discarded, I would explicitly call Dispose() on it. You don't need IDisposable for that, but it's harmless.