Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

How to: Coordinate Multiple Threads of Execution

In order for your multithreaded components to be thread-safe, you must coordinate access to shared resources. If multiple threads attempt to access a shared resource at the same time, race conditions can result, causing corruption of data. You can avoid race conditions by using locks. For details on thread-safety and race conditions, see Thread-Safe Components.

To create a lock on an object

  1. Identify the code that must be executed atomically and the object on which the code will be executed. For details, see Thread-Safe Components

  2. Place a lock on that object and enclose your code inside that lock.

    This code will now be executed atomically on the locked object.

    SyncLock MyObject   ' This represents the start of the lock on MyObject.
    ' Insert code to be executed atomically on MyObject here.
    End SyncLock   ' This represents the end of the lock.
    

    lock (MyObject) 
       // All code inside the braces {} is executed with MyObject locked.
    {
       // Insert code to be executed atomically on MyObject here.
    }
    

Community Additions

ADD
Show:
© 2015 Microsoft