尝试将从二进制文件读取的元素添加到BindingList<Type>
时,我遇到了一个奇怪的问题。这是错误的代码:
BindingList<Type> tmpList = null;
using (FileStream serializedListStream = File.OpenRead(_kReificableDroidsListPath))
{
BinaryFormatter serializer = new BinaryFormatter();
//Temporary list so that ListChanged event is fired
//upon adding new types
tmpList = serializer.Deserialize(serializedListStream) as BindingList<Type>;
foreach (Type droidType in tmpList)
{
ReificableDroids.Add(droidType);
}
}
Visual Studio调试器向我显示此异常:
System.IO.IOException: The process cannot access the file 'C:\Users\Zoneur\documents\visual studio 2012\Projects\Droid TP1\Droid TP2\bin\Debug\reificable_droids_list.bin' because it is being used by another process.
我理解的是该文件需要关闭,所以我从foreach
语句中取出using
循环,如下所示:
BindingList<Type> tmpList = null;
using (FileStream serializedListStream = File.OpenRead(_kReificableDroidsListPath))
{
BinaryFormatter serializer = new BinaryFormatter();
//Temporary list so that ListChanged event is fired
//upon adding new types
tmpList = serializer.Deserialize(serializedListStream) as BindingList<Type>;
}
foreach (Type droidType in tmpList)
{
ReificableDroids.Add(droidType);
}
不再抛出异常,但我无法理解问题是什么...... ReificableDroids
是BindingList<Type>
类型的属性。
另外,如果我在foreach
语句中保留using
循环,只需将类型名称打印到控制台:
foreach (Type droidType in tmpList)
{
Console.WriteLine(droidType.GetType().ToString());
}
也没有抛出异常。
有没有人知道什么可能导致在使用语句中抛出此异常?
答案 0 :(得分:1)
我没有看到此异常与您在循环加载数据的位置有任何关系。它必须是相关的东西,这里没有显示。
清单:
AddingNew
的{{1}}或ListChanged
个事件,并可能再次从那里访问该文件?