RndThreadFunc)
rndthreads(i).Start()
Next i
End Sub
End Class
Notice that you perform all access to the numberThreads variable in the form of an object
lock. Before each access, the accessor must obtain the lock on the theLock object instance. The
type of theLock field is of type Object simply because its actual type is inconsequential. The
only thing that matters is that it is a reference type??”that is, an instance of an Object rather
than a value type. Since you only need the Object instance to utilize its internal sync block,
you can just instantiate an object of type System.Object.
One thing you??™ve probably also noticed is that the code is uglier than the version that used
the Interlocked methods. Whenever you call Monitor.Enter(), you want to guarantee that the
matching Monitor.Exit() executes no matter what. The examples mitigate this problem using
the Interlocked class by wrapping the usage of the Interlocked class methods within a class
named SpinLockManager. Can you imagine the chaos that could ensue if a Monitor.Exit() call
was skipped because of an exception? Therefore, you always want to utilize a Try/Finally block
in these situations. The VB language creators recognized that developers were going through a
lot of effort to ensure that these Finally blocks were in place when all they were doing was calling
Monitor.
Pages:
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474