14 September 2012

SyncLock and Lock in C#

SyncLock and Lock in C#


The lock (C#) and SyncLock (Visual Basic) statements can be used to ensure that a block of code runs to completion without interruption by other threads. This is accomplished by obtaining a mutual-exclusion lock for a given object for the duration of the code block.

lock or SyncLock statement is given an object as an argument, and is followed by a code block that is to be executed by only one thread at a time. For example:

public class TestThreading
{
    private System.Object lockThis = new System.Object();

    public void Process()
    {

        lock (lockThis)
        {
            // Access thread-sensitive resources.
        }
    }

}





No comments:

Post a Comment

Comments Welcome

Implementing OAuth validation in a Web API

 I mplementing OAuth validation in a Web API Implementing OAuth validation in a Web API using C# typically involves several key steps to sec...