Home > Software design >  Two threads trying to access same List :" System.ArgumentOutOfRangeException"
Two threads trying to access same List :" System.ArgumentOutOfRangeException"

Time:10-19

I am new to threading . I have a List and 2 threads T1 and T2.

private readonly List<item> myCompletedItems;

I have a method which sets the collection

public void ItemCreated(item theitem)
{
this.myCompletedItems.add(theitem);
}

I have another method which gets a field value of first item:

public int GetStartItemId()
{          
  return this.myCompletedItems[0].id;                
}

Thread 1 is adding items to "myCompletedItems".But even before an item is added to list, Thread 2 is trying to access the list and throwing "System.ArgumentOutOfRangeException: Index was out of range". How do i make Thread 2 wait until all the items are added to list by Thread 1?

CodePudding user response:

Regular lists are not thread safe, and just about anything can happen when trying to use it from multiple threads concurrently.

How do i make Thread 2 wait until all the items are added to list by Thread 1?

Use a lock if you want to ensure two threads does not access the resource concurrently, or a manualResetEvent/autoResetEvent to block a thread until another thread does something.

Or more practically, use concurrent collections.

However, multi threading is not a good place to mess around and try things randomly. This will very easily result in bugs that are very hard to reproduce. Multi threading is difficult even for experienced programmers, and you should have a fairly good knowledge of potential hazards like deadlocks and race conditions before trying to use multi threading. See also asynchronous programming and DataFlow, these are in part done to avoid the need for manual synchronization between threads.

  • Related