使用NDepend,我们如何从依赖矩阵中删除由于任务(TPL)而由编译器生成的循环依赖?

时间:2013-05-11 17:19:37

标签: c# task-parallel-library ndepend

使用NDepend,我们如何从依赖矩阵中删除由于任务(TPL)而由编译器生成的循环依赖。

如果我们无法删除它们,那么我们如何轻松地将它们与需要我们注意的重要循环依赖性区分开来。

有没有关于处理编译器生成的循环依赖性的最佳实践?

编辑:

编译器生成的依赖循环可以在图的左上角看到

The compiler generated dependency cycle can be observed in the top left of the diagram

生成依赖循环的代码(在.Net 4.0中编译)

* logger是我班级的一个字段

  private void WriteJsonFileToDiskAsync(string filePath, string json)
    {
        Task.Factory.StartNew(() => WriteJsonFileToDisk(filePath, json))
            .ContinueWith(HandleWriteException);
    }

    private void WriteJsonFileToDisk(string filePath, string json)
    {
        Stream fileStream = null;
        try
        {
            fileStream = File.Create(filePath);
            using (var writer = new StreamWriter(fileStream))
            {
                fileStream = null;
                writer.Write(json);
            }

            logger.InfoIfDebuggerIsAttached(string.Format(CultureInfo.InvariantCulture, "Persisted file: {0}", filePath));
        }
        finally
        {
            if (fileStream != null)
                fileStream.Dispose();
        }
    }

    private static void HandleWriteException(Task task)
    {
        if (task.IsFaulted)
        {
            //TODO: Handle Exception
        }
    }

1 个答案:

答案 0 :(得分:1)

Alexandre,在编译源代码后,我获得了以下依赖矩阵:

enter image description here

我们可以看到编译器生成了一个在Program内声明的子类型。这个名为Program+<>c__DisplayClass1的生成类型只是编译器体操,它不是源代码的一部分。这不是一个问题,这两种类型都是相互依赖的,你不能做太多的事情。

要放弃生成的类型,您可以编写类似...

的查询
from t in Application.Types
where !t.IsGeneratedByCompiler
select t

...然后将部分结果导出到Matrix:

enter image description here

最后,我想补充说,相互依赖的类型在一般情况下不是问题。大多数众所周知的GoF design patterns都需要相互依赖的类型。

问题在于您有相互依赖的组件,特别是如果这些组件是名称空间。有关此主题的two white-books可在NDepend网站上公开获取。

相互依赖的类型是一个问题的一种情况是基类使用衍生物(对此有默认的CQLinq规则Base class should not use derivatives