属性函数抛出异常

时间:2013-09-18 19:46:00

标签: c# winforms properties

我有一个公共属性,它暴露了一个类管理器(ViewManager),它管理哪些用户可以使用哪些视图。此属性(以及其他几个)调用一个名为PopulateCollections()的函数,然后返回私有字段_Views。

private bool _CollectionsPopulated = false;
public ViewManager Views { get { PopulateCollections(); return _Views;}}
void PopulateCollections()
{
    if (_CollectionsPopulated) return;
    _CollectionsPopulated = true;
    foreach (ClassTable item in ClassessTables)
    {
        item.ReflectMe();
    }
}

ClassTable是另一个在数据库表中存储类结构的类。 函数ReflectMe()调用每个类项来获取每个类的attrbiutes。

所有这些代码都很有效。 我的问题是时间问题。

当代码运行时,99%的时间我都没有问题。但是对于那个1%,PopulateCollections()函数花费的时间太长而导致异常。

通过每个可用的模型进行解析(每个模型都有自己的ClassesTables组)时,我到达了这一点,我正在查看视图......

If  ((ThisModel != null) && (ThisModel.Views != null))
{
    //Code here
}

当它第一次触发Pop ThisCollections的“ThisModel.Views”时,当我将鼠标悬停在ThisModel.Views上时,我得到以下内容:

  

“'ThisModel.Views'引发了'System.InvalidOperationException'类型的异常”

然而,经过一秒钟后,当我再次悬停在它上面时,我得到了我期待的实际值。这告诉我PopulateCollections()代码仍然反映每个类,因为当我在没有调试的情况下运行它时,引发的异常是

  

“集合已被修改;枚举操作可能无法执行。”

那么......在完成此方法之前,如何使代码明确等待?

2 个答案:

答案 0 :(得分:1)

我认为欺骗的是你的_CollectionsPopulated标志并不真正表明该集合是完全填充的。当您快速连续两次调用Views属性时,即使仍在创建集合,它也会第二次返回。

我建议添加另一个跟踪集合状态的标志。如果集合处于填充状态,请不要尝试重新填充,而是返回null

private bool _collectionsPopulating = false;
private bool _CollectionsPopulated = false;
public ViewManager Views 
{ 
     get 
     { 
         if (_collectionsPopulating) return null;
         PopulateCollections(); 
         return _collectionsPopulat_Views;
     }
}

void PopulateCollections()
{
    if (_CollectionsPopulated) return;
    _collectionsPopulating = true;
    foreach (ClassTable item in ClassessTables)
    {
        item.ReflectMe();
    }
    _CollectionsPopulated = true;
    _collectionsPopulating = false;
}

答案 1 :(得分:0)

我的解决方案来自左栏...正在填充的CLASS是问题。然而,代码并没有告诉我这个,之后代码就像它最初的工作顺利一样。

相关问题