2

So, this question asks how to threadsave lists. To sum it up, instead of using

List<int[]> listName = new List<int[]>();

//you use:

SynchronizedCollection<int[]> listName = new SynchronizedCollection<int[]>();

But my problem is, that if I use:

int[] returnArray = new int[listName[0].Length];

I can't access those elements with indexing. How can I access them then? Is there not a way to make lists threadsafe without loosing any functionality?

Maybe I can work with limited functionality, I only need 4 things: reading the lowest and the highest elements (only those), deleting listName[0] and adding something on top. So I don't need any of the elements in the middle actually. But there are 2 threads and depending on what the thread did it will either add a new one on top and take it or delete the lowest one and take the new lowest one.

I can't use queues or stacks because of this, so I am all out of ideas.

Now the question is, is there something that fills those requirements?

bv_Martn
  • 139
  • 12
  • 1
    It doesn't sound like the problem is which collection type to use, although it's a little bit unclear. This might get easier if you look at how to control access to the collection to make sure that the simultaneous modifications you're concerned about can't happen. – Scott Hannen May 06 '19 at 12:54

1 Answers1

3

You can use lock to access an object from multiple threads

Nik.
  • 96
  • 4
  • Do you mean lock it in order to keep it from being edited by multiple threads? – bv_Martn May 06 '19 at 12:46
  • 2
    I would start with this. If you start with some locks just to ensure that the simultaneous access you're concerned about can't happen then it might be a lot easier than trying to find a specific collection type. If you get some version of it that works - even if it doesn't look optimal - then you've got a starting point to make changes or show someone what problems it solves. (Or that solution might just be good enough as-is.) – Scott Hannen May 06 '19 at 12:56
  • 1
    @bv_Martn, `SynchronizedCollection` uses the `lock` underneath so there is no significant difference of using `lock` or `SynchronizedCollection` from the final result perspective. – Dmytro Mukalov May 06 '19 at 13:08
  • @DmytroMukalov well yes but then I can not use indices – bv_Martn May 06 '19 at 13:22
  • 1
    @bv_Martn, why cannot you use the indices with lock ? I meant that you can effectively substitute `SynchronizedCollection` which `lock`. – Dmytro Mukalov May 06 '19 at 13:25
  • @DmytroMukalov oh yes, you're right. that is how i solved i – bv_Martn May 06 '19 at 14:04