foreach & arraylist

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Lloyd Dupont

    #1

    foreach & arraylist

    Does any of you have the slightest ideas of why you can't modify an array
    list while in a foreach of its element.

    I wrote my own collection and I'm trying to add the same behavior but I
    don't know where to start.

    I though to internal events but dismiss the idea because it prevents garbage
    collection of the enumerator.
    any other ideas ?


  • Daniel O'Connell

    #2
    Re: foreach & arraylist


    "Lloyd Dupont" <net.galador@ld > wrote in message
    news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=blue]
    > Does any of you have the slightest ideas of why you can't modify an array
    > list while in a foreach of its element.
    >[/color]
    Because that is the rules when it comes to enumerators, it makes enumerator
    implementation alot easier. Allowing changes requires a more sophisticated,
    thread-safe enumerator. The probability of a bug in that case would be very
    large in deed.[color=blue]
    > I wrote my own collection and I'm trying to add the same behavior but I
    > don't know where to start.
    >
    > I though to internal events but dismiss the idea because it prevents[/color]
    garbage[color=blue]
    > collection of the enumerator.
    > any other ideas ?
    >[/color]
    Well, simple method, stick a private field like int version; in your class
    and increment it on every change, following your proper locking rules and
    methodologies of course(you may need to use
    System.Threadin g.Interlocked.I ncrement in this case, assuming multiple
    threads, enumerators, and processors). Then on every command to the
    enumerator check that value, if it changed since the enumerator was created,
    your enumerator is invalid and should throw an exception as specified in the
    IEnumerable documentation.

    [color=blue]
    >[/color]


    Comment

    • Daniel O'Connell

      #3
      Re: foreach &amp; arraylist


      "Lloyd Dupont" <net.galador@ld > wrote in message
      news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=blue]
      > Does any of you have the slightest ideas of why you can't modify an array
      > list while in a foreach of its element.
      >
      > I wrote my own collection and I'm trying to add the same behavior but I
      > don't know where to start.
      >
      > I though to internal events but dismiss the idea because it prevents[/color]
      garbage[color=blue]
      > collection of the enumerator.
      > any other ideas ?
      >[/color]
      I forgot to mention, you could probably use internal events. foreach will
      call IDisposable.Dis pose if the enumerator implements IDisposable, so you
      could use that call to clean up, its not as clean but it would work.[color=blue]
      >[/color]


      Comment

      • Kalpesh Shah

        #4
        Re: foreach &amp; arraylist

        The usage of "in" keyword doesnt let you modify the content of the
        arraylist.

        As far as valuetype such as int,bool are concerned, they might be
        modifiable.

        But when objects are added to the arraylist, the "in" keyword in forach,
        returns a read-only reference, which you cant make it point to other
        reference

        One cant change the behaviour of "in", since its a keyword & not an operator


        for eg
        foreach (person p in alist)
        p = new person("my name"); // this cant be done, because p is
        read-only here (as the compiler says)

        but you can do the following

        foreach (person p in alist)
        p.name = "new name";

        If you want to store a new reference in alist
        for(int i =0; i < alist.Count; i++)
        alist[i] = new person("new name") // now this can be done, since it is
        using subscript operator, which returns an object instance

        I hope I answered, what you wanted. If anything is unclear, do write back on
        the group
        I am no expert though, but my understanding tells me this way to achieve it

        HTH
        Kalpesh


        "Lloyd Dupont" <net.galador@ld > wrote in message
        news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=blue]
        > Does any of you have the slightest ideas of why you can't modify an array
        > list while in a foreach of its element.
        >
        > I wrote my own collection and I'm trying to add the same behavior but I
        > don't know where to start.
        >
        > I though to internal events but dismiss the idea because it prevents[/color]
        garbage[color=blue]
        > collection of the enumerator.
        > any other ideas ?
        >
        >[/color]




        Comment

        • Lloyd Dupont

          #5
          Re: foreach &amp; arraylist

          I like this int version inside a list, but if my list is gong to be used in
          multithreaded environment, ain't all these lock() {} going to be a
          performance hit ?

          "Daniel O'Connell" <onyxkirx@--NOSPAM--comcast.net> a écrit dans le message
          de news:fTrib.5506 41$Oz4.497665@r wcrnsc54...[color=blue]
          >
          > "Lloyd Dupont" <net.galador@ld > wrote in message
          > news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=green]
          > > Does any of you have the slightest ideas of why you can't modify an[/color][/color]
          array[color=blue][color=green]
          > > list while in a foreach of its element.
          > >[/color]
          > Because that is the rules when it comes to enumerators, it makes[/color]
          enumerator[color=blue]
          > implementation alot easier. Allowing changes requires a more[/color]
          sophisticated,[color=blue]
          > thread-safe enumerator. The probability of a bug in that case would be[/color]
          very[color=blue]
          > large in deed.[color=green]
          > > I wrote my own collection and I'm trying to add the same behavior but I
          > > don't know where to start.
          > >
          > > I though to internal events but dismiss the idea because it prevents[/color]
          > garbage[color=green]
          > > collection of the enumerator.
          > > any other ideas ?
          > >[/color]
          > Well, simple method, stick a private field like int version; in your class
          > and increment it on every change, following your proper locking rules and
          > methodologies of course(you may need to use
          > System.Threadin g.Interlocked.I ncrement in this case, assuming multiple
          > threads, enumerators, and processors). Then on every command to the
          > enumerator check that value, if it changed since the enumerator was[/color]
          created,[color=blue]
          > your enumerator is invalid and should throw an exception as specified in[/color]
          the[color=blue]
          > IEnumerable documentation.
          >
          >[color=green]
          > >[/color]
          >
          >[/color]


          Comment

          • Grant Richins [MS]

            #6
            Re: foreach &amp; arraylist

            Yes a lot of spurious locks would slow you down, but this is the perfect
            place to use System.Threadin g.Interlocked.I ncrement(ref int).

            --
            --Grant
            This posting is provided "AS IS" with no warranties, and confers no rights.


            Comment

            • Daniel O'Connell

              #7
              Re: foreach &amp; arraylist


              "Lloyd Dupont" <net.galador@ld > wrote in message
              news:OIy1u6XkDH A.2964@tk2msftn gp13.phx.gbl...[color=blue]
              > I like this int version inside a list, but if my list is gong to be used[/color]
              in[color=blue]
              > multithreaded environment, ain't all these lock() {} going to be a
              > performance hit ?
              >[/color]
              Yes. I however advised using the proper locking because I didn't know what
              you were doing precisely. If your class requires locking in other
              situations(it needs to be thread safe, for example) then use locks, if not,
              Interlocked.Inc rement(ref int) is quite sufficent for simply incrementing
              the version field.[color=blue]
              > "Daniel O'Connell" <onyxkirx@--NOSPAM--comcast.net> a $BqD(Brit dans le[/color]
              message[color=blue]
              > de news:fTrib.5506 41$Oz4.497665@r wcrnsc54...[color=green]
              > >
              > > "Lloyd Dupont" <net.galador@ld > wrote in message
              > > news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=darkred]
              > > > Does any of you have the slightest ideas of why you can't modify an[/color][/color]
              > array[color=green][color=darkred]
              > > > list while in a foreach of its element.
              > > >[/color]
              > > Because that is the rules when it comes to enumerators, it makes[/color]
              > enumerator[color=green]
              > > implementation alot easier. Allowing changes requires a more[/color]
              > sophisticated,[color=green]
              > > thread-safe enumerator. The probability of a bug in that case would be[/color]
              > very[color=green]
              > > large in deed.[color=darkred]
              > > > I wrote my own collection and I'm trying to add the same behavior but[/color][/color][/color]
              I[color=blue][color=green][color=darkred]
              > > > don't know where to start.
              > > >
              > > > I though to internal events but dismiss the idea because it prevents[/color]
              > > garbage[color=darkred]
              > > > collection of the enumerator.
              > > > any other ideas ?
              > > >[/color]
              > > Well, simple method, stick a private field like int version; in your[/color][/color]
              class[color=blue][color=green]
              > > and increment it on every change, following your proper locking rules[/color][/color]
              and[color=blue][color=green]
              > > methodologies of course(you may need to use
              > > System.Threadin g.Interlocked.I ncrement in this case, assuming multiple
              > > threads, enumerators, and processors). Then on every command to the
              > > enumerator check that value, if it changed since the enumerator was[/color]
              > created,[color=green]
              > > your enumerator is invalid and should throw an exception as specified in[/color]
              > the[color=green]
              > > IEnumerable documentation.
              > >
              > >[color=darkred]
              > > >[/color]
              > >
              > >[/color]
              >
              >[/color]


              Comment

              • Lloyd Dupont

                #8
                Re: foreach &amp; arraylist

                no worry I had an idea last night.
                I lock in upper level user code, and the usage is preasumably safe.

                on another though this Interlocked class, looks great, it works across
                thread, but does it work across process ?
                I was thinking to use a shared memory channel to share data but I've heard
                that mutex was a performance hit and I had better design my own custom user
                level "mutex"

                "Grant Richins [MS]" <grantri@online .microsoft.com> wrote in message
                news:uuufF6bkDH A.2416@TK2MSFTN GP10.phx.gbl...[color=blue]
                > Yes a lot of spurious locks would slow you down, but this is the perfect
                > place to use System.Threadin g.Interlocked.I ncrement(ref int).
                >
                > --
                > --Grant
                > This posting is provided "AS IS" with no warranties, and confers no[/color]
                rights.[color=blue]
                >
                >[/color]


                Comment

                • William Stacey

                  #9
                  Re: foreach &amp; arraylist

                  If your going to have multiple threads against a queue (for example) at the
                  same time, then you need to lock to keep things straight. Here is an
                  example of using multiple readers against a Queue. I derived a class from
                  Queue to change the end of queue behavior to return null instead of
                  Exception. Also, in the new Iterator, we treat the queue as a queue and not
                  as an array with a fixed size. These two things combined, allow us to have
                  one thread add items and multiple threads removing items (if order of
                  objects in not important) or any combination. Notice each thread can use
                  "foreach" and not throw a version exception, which is what we want here.
                  HTH
                  --William Stacey, MVP

                  //Put in a button event or main, etc.
                  Queue mysyncQueue = Queue.Synchroni zed(new MyQueue()); //Get a Sync'd
                  version of my derived Queue class.
                  for (int i = 1; i <= 30; i++) //Put some data in it.
                  {
                  mysyncQueue.Enq ueue("Item"+i);
                  }
                  StringBuilder sbResults = new StringBuilder() ;
                  ThreadWorkerCla ss threadWorker1 = new ThreadWorkerCla ss("Thread1",
                  sbResults, mysyncQueue);
                  ThreadWorkerCla ss threadWorker2 = new ThreadWorkerCla ss("Thread2",
                  sbResults, mysyncQueue);
                  Thread thread1 = new Thread(new ThreadStart(thr eadWorker1.Run) );
                  Thread thread2 = new Thread(new ThreadStart(thr eadWorker2.Run) );
                  thread1.IsBackg round = true;
                  thread2.IsBackg round = true;
                  thread1.Start() ;
                  thread2.Start() ;
                  thread1.Join();
                  thread2.Join();
                  Console.WriteLi ne("Two threads read the following items from the shared
                  queue.");
                  Console.WriteLi ne(sbResults);
                  Console.WriteLi ne("Queue up some more items and print.");
                  mysyncQueue.Enq ueue("MoreItem1 ");
                  mysyncQueue.Enq ueue("MoreItem2 ");
                  foreach(string s in mysyncQueue)
                  {
                  Console.WriteLi ne(s);
                  }
                  //End above.

                  //Create a worker class that reads from shared queue.
                  public class ThreadWorkerCla ss
                  {
                  private StringBuilder sbResults;
                  private Queue sharedQueue;
                  private string threadName;
                  public ThreadWorkerCla ss(string threadName, StringBuilder sbResults, Queue
                  sharedQueue)
                  {
                  this.threadName = threadName;
                  this.sbResults = sbResults;
                  this.sharedQueu e = sharedQueue;
                  }
                  public void Run()
                  {
                  int count = 1;
                  foreach(string s in sharedQueue)
                  {
                  sbResults.Appen d(threadName + " Dequeued: " + s + "\r\n");
                  if ( threadName == "Thread1" )
                  {
                  //Give thread1 more time, but only allow it to read 10 items.
                  if ( ++count >= 10 )
                  break;
                  Thread.Sleep(5) ;
                  }
                  else
                  Thread.Sleep(10 ); //Let thread2 sleep for longer to mix-up the reads a
                  bit.
                  }
                  sbResults.Appen d(threadName + " ended getting data from the queue.\r\n");
                  }
                  } //End ThreadWorkerCla ss

                  //Derive a Queue and override the Dequeue behavior.
                  //Also setup a enumerator that will allow threads to add to and remove items
                  from
                  //queue while we iterate over it.
                  public class MyQueue : Queue
                  {
                  public MyQueue() : base()
                  {
                  }
                  public MyQueue(ICollec tion col) : base(col)
                  {
                  }
                  public MyQueue(int capacity) : base(capacity)
                  {
                  }
                  public MyQueue(int capacity, float growFactor) : base(capacity, growFactor)
                  {
                  }
                  public override IEnumerator GetEnumerator()
                  {
                  return new MyQueueEnumerat or(this);
                  }
                  public override object Dequeue()
                  {
                  object obj;
                  try
                  {
                  obj = base.Dequeue();
                  }
                  catch(InvalidOp erationExceptio n)
                  {
                  return null; //If empty, change behavior to return null instead of
                  exception.
                  }
                  catch(Exception e)
                  {
                  throw e;
                  }
                  return obj;
                  }
                  private class MyQueueEnumerat or : IEnumerator, ICloneable
                  {
                  private Queue queue;
                  private object currentElement;

                  internal MyQueueEnumerat or(Queue queue) : base()
                  {
                  this.queue = queue;
                  if ( this.queue == null )
                  throw new ArgumentNullExc eption("queue", "queue argument is null.");
                  currentElement = this.queue; //flag to state enum is not started yet.
                  }
                  public virtual bool MoveNext()
                  {
                  if ( ((currentElemen t = queue.Dequeue() ) == null) && (queue.Count == 0) )
                  //Is queue empty?
                  {
                  this.currentEle ment = this.queue;
                  return false;
                  }
                  return true;
                  }
                  public virtual void Reset()
                  {
                  this.currentEle ment = this.queue; //reset enum flag to closed state.
                  }
                  public virtual object Current
                  {
                  get
                  {
                  if (currentElement == this.queue) //enum reset or started with no
                  MoveNext?
                  {
                  throw new InvalidOperatio nException("Inv alidOperation_E numNotStarted") ;
                  }
                  return currentElement;
                  }
                  }
                  public object Clone()
                  {
                  return base.Memberwise Clone();
                  }
                  } //End QueueEnumerator
                  } //End MyQueue


                  Comment

                  • Lloyd Dupont

                    #10
                    Re: foreach &amp; arraylist

                    I don't understand what you said.
                    would you ind tell it otherwise ?

                    "Kalpesh Shah" <shahkalpesh@ho tmail.com> wrote in message
                    news:%23HpzNBWk DHA.2312@TK2MSF TNGP12.phx.gbl. ..[color=blue]
                    > The usage of "in" keyword doesnt let you modify the content of the
                    > arraylist.
                    >
                    > As far as valuetype such as int,bool are concerned, they might be
                    > modifiable.
                    >
                    > But when objects are added to the arraylist, the "in" keyword in forach,
                    > returns a read-only reference, which you cant make it point to other
                    > reference
                    >
                    > One cant change the behaviour of "in", since its a keyword & not an[/color]
                    operator[color=blue]
                    >
                    >
                    > for eg
                    > foreach (person p in alist)
                    > p = new person("my name"); // this cant be done, because p is
                    > read-only here (as the compiler says)
                    >
                    > but you can do the following
                    >
                    > foreach (person p in alist)
                    > p.name = "new name";
                    >
                    > If you want to store a new reference in alist
                    > for(int i =0; i < alist.Count; i++)
                    > alist[i] = new person("new name") // now this can be done, since it is
                    > using subscript operator, which returns an object instance
                    >
                    > I hope I answered, what you wanted. If anything is unclear, do write back[/color]
                    on[color=blue]
                    > the group
                    > I am no expert though, but my understanding tells me this way to achieve[/color]
                    it[color=blue]
                    >
                    > HTH
                    > Kalpesh
                    >
                    >
                    > "Lloyd Dupont" <net.galador@ld > wrote in message
                    > news:ea8V0QUkDH A.2268@TK2MSFTN GP12.phx.gbl...[color=green]
                    > > Does any of you have the slightest ideas of why you can't modify an[/color][/color]
                    array[color=blue][color=green]
                    > > list while in a foreach of its element.
                    > >
                    > > I wrote my own collection and I'm trying to add the same behavior but I
                    > > don't know where to start.
                    > >
                    > > I though to internal events but dismiss the idea because it prevents[/color]
                    > garbage[color=green]
                    > > collection of the enumerator.
                    > > any other ideas ?
                    > >
                    > >[/color]
                    >
                    >
                    >
                    >[/color]


                    Comment

                    Working...