当前位置: 动力学知识库 > 问答 > 编程问答 >

C#/ASP.Net modifying lists... will this cause problems?

问题描述:

So here's my problem:

I have a static list of objects that stores all the files being uploaded.

private static List<Upload> vidUploadList = new List<Upload>();

To maintain the list, any uploads that have failed should be removed from the list. My question is: if a user changes the list, the index of items in the list will change. Is it possible for another user to be half way through a list using a loop command and have the list change? If say, the item [3] in the list was being used and then the object before was removed (changing the position to [2]) would the code still run?

Is it possible to lock the list when any user comes to use it and then release the lock straight after, ensuring that only one session at a time is accessing the list? I have heard that the monitor class may help me here.

网友答案:

would the code still run?

NO, an InvalidOperationException "Collection was modified; enumeration operation may not execute" would be thrown

you can actually try it with this simple code

List<int> test = new List<int>(){ 1, 2, 3, 4, 5};
foreach(int i in test)
    test.Remove(i); //Exception

If you really wish to allow multiple users to edit it then consider using a ConcurrentCollection such as a ConcurrentBag

网友答案:

When I used C# in Visual Studio 2013, the compiler would complain if it was obvious that the list was being changed while looping through it using foreach. But if you find the size of the list and loop through it using a for loop, I don't think the compilation will fail. But it is still not good practice because the execution could be erratic. Here is a link to how to lock your list.

分享给朋友:
您可能感兴趣的文章:
随机阅读: