Use Synchronization Code with Multiple Threads

Problem

You need to access the same object from multiple threads, without causing a concurrency problem.

Solution

Use the SyncLock statement to gain exclusive access to the object.

Discussion

Trying to access an object on more than one thread at once is inherently dangerous, because a single command in a high-level language like Visual Basic .NET might actually compile to dozens of low-level machine language instructions. If two threads try to modify data at the same time, there’s a very real possibility that the changes made by one thread will be overwritten—and this is only one of many possible threading errors, all of which occur sporadically and are extremely difficult to diagnose.

To overcome these ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.