user959883
user959883

Reputation:

Locking a Static Method in C#

I want to lock a static method in C# , an alternate to synchronization in java .

Following is the method

public synchronized static  void UpdateDialListFile(String filePath, int lineno,
        String lineToBeInserted)

Now i am implementing this function in C# , How the alternative to synchronized will work in C#

The above method is being called from within a thread as

 new DialList(oDialInfo.FileName,oDialInfo.AppId,oDialInfo.AppCode,
        pausetime,oDialInfo, PropVal).start();

Upvotes: 1

Views: 1388

Answers (3)

Kevin
Kevin

Reputation: 704

You can also use Monitor.Enter and Monitor.Exit to lock a critical section.

Upvotes: 0

Nicholas Carey
Nicholas Carey

Reputation: 74257

You can use the lock statement like this to serialize access to critical sections or resources. The scope/meaning of the guard object is entirely up to you:

public class Widget
{
  // scope of 'latch'/what it represents is up to you.
  private static readonly object latch = new object() ;

  public void DoSomething()
  {
    DoSomethingReentrant() ;

    lock ( latch )
    {
       // nobody else may enter this critical section
       // (or any other critical section guarded by 'latch'
       // until you exit the body of the 'lock' statement.
       SerializedAccessDependentUponLatch() ;
    }
    DoSomethingElseReentrant() ;
    return ;
  }
}

Other synchronization primitives available in the CLR are listed at http://msdn.microsoft.com/en-us/library/ms228964(v=vs.110).aspx

Upvotes: 1

DarthVader
DarthVader

Reputation: 55032

[MethodImpl(MethodImplOptions.Synchronized)]

you can use this if you want to synchronize the whole method.

Similar question:

C# version of java's synchronized keyword?

Upvotes: 3

Related Questions