1

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();
H H
  • 263,252
  • 30
  • 330
  • 514

3 Answers3

3

[MethodImpl(MethodImplOptions.Synchronized)]

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

Similar question:

C# version of java's synchronized keyword?

Community
  • 1
  • 1
DarthVader
  • 52,984
  • 76
  • 209
  • 300
  • thanks and you mentioned if i want to synchronize whole method . what are other possible ways if i want to lock a part of method ? –  Sep 04 '12 at 19:00
  • look at synchronization in c#. there are many ways. depends on what you need. `lock` is one you can start with. – DarthVader Sep 04 '12 at 19:02
1

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

Nicholas Carey
  • 71,308
  • 16
  • 93
  • 135
0

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

Kevin
  • 704
  • 3
  • 4