Wednesday, December 16, 2009

synchronize method in dotNet c# - Method Synchronization

Synchronized methods give us an ability to execute only one thread at a time. This is useful if our method modifies global variable.

using System.Runtime.CompilerServices;

[MethodImpl(MethodImplOptions.Synchronized)]
public Boolean Check()
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}

Its similar to java like... for Java it will be...

public class SynchronizedCounter {
private int c = 0;

public synchronized void increment() {
c++;
}
}

Simply........

Specifies that the method can be executed by only one thread at a time. Static methods lock on the type, while instance methods lock on the instance. Onlyone thread can execute in any of the instance functions and only one thread can execute in any of a class's static functions.

No comments:

Post a Comment