c# - System.Timers.Timer throwing an Exception -


i implementing code using list<>. each list has class type item. 1 of members of class system.timer.timer variable called "timeout". timeout.interval value 10 , timeout.elapsed event should triggered every timeout.interval (which 10).

the event delete item list. event overloaded such that

timeout.elapsed += (sender, e) => deleteentry(sender, e, i) 

where index of item in list.

for event method,

public void deleteentry(object sender, system.timers.elapsedeventargs e, int i) {     //delete item list     listtable.removeat(i); } 

my problem if 2 items started timer , decided call eventhandler after same specified interval, 1 added list first deleted, , when second 1 called immediately., throws error telling me index out of bounds. happens because 1 of items deleted, lists shifted index , and "i" sent deleteentry method old 1 no longer existent.

in other cases when have more 2 items in list, deletes wrong 1 since method uses wrong index.

using arrays not option me. work de-fragment array every deletion of element.

how can solve this? need threadpool, setting flag or that? can synchronizingobject property in anyway?

thank you.

solution:

from saying seems problem list shifting , don't know @ point item is. if case want access count property of list tells amount of items in list. careful working not account indexing of 0.

solution:

from saying seems problem list shifting , don't know @ point item is. if case want access count property of list tells amount of items in list. careful working not account indexing of 0.

edit:

example:

    private static list<int> numbers = new list<int>();     private static readonly object numberslock = new object();     static void main(string[] args)     {         thread x = new thread(() => {             addnumbers();         });          thread y = new thread(() => {             addnumbers();         });          x.start();         y.start();     }      private static void addnumbers() {         random r = new random(datetime.utcnow.millisecond);          while (true) {             lock (numberslock) {                 numbers.add(r.next(0, 100));             }         }     } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -