Domanda

Normally, to access a shared variable when multithreading, we need to do the following and synchronize it:

'''This is VB code. 
'Lock variable to request access and wait. 
Monitor.Enter(list1)
Try
    list1.item(i) = 42
Finally
  Monitor.Exit(Me)
End Try

But do i need to do this locking in this case where I want to add an element to a List at a specific i? This i value will only be edited once, so I don't need to worry about an index being changed twice.

And what happens if it was an Array or an ArrayList, that I set? What is the fastest to use if I am sure to not edit an index twice?

È stato utile?

Soluzione

Modifying an element of the List does not in any way alter the internal state of the List object. In other words, the code cannot corrupt the List object itself so locking isn't necessary for that.

However, it is entirely unpredictable when another thread that iterates the List is going to be able to observe the changed element. With very good odds that it will see a stale or partially updated value of the list element. The element type matters a great deal, it needs to be atomic to avoid the case where another thread sees a partially updated value. Only value types of Integer or less and reference type references are guaranteed to be atomic. Both the staleness and the atomicity problems almost always require locking to avoid undebuggable and random failure.

Altri suggerimenti

If you are not worried about multiple threads changing the same object, you dont even need to do locking. I dont think I have ever used locking for items that already exist (except for a very special case), just for changing the size of my array/collection (in this case).

BTW, you should look into SYNCLOCK They are essentially the same. MS says, "The functionality provided by the Enter and Exit methods is identical to that provided by the C# lock statement (SyncLock in Visual Basic), except that lock and SyncLock wrap the Exit method in a try…finally block (Try…Finally in Visual Basic) to ensure that the monitor is released."

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top