Home

synchronize method in dotNet c#

E-mail Print
Share/Save/Bookmark
Synchronized methods give us an ability to execute only one thread at a time. This is useful if our method modifies global variable.

If we have a number of available product items to sell in a variable quantity. What will happen when quantity = 1 and two users access it at the same time (both want to buy 1 item - that is decrease variable by one)?!

public Boolean Check()
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}
As both users access at the same time, condition will be for both true and program will decrease quantity. Resulting in overselling our available stock.

When we use synchronized methods, only one thread at time is possible. Program will carry out request of user one, other user request will wait. After first request is carried out, second request will be handled.

using System.Runtime.CompilerServices;

[MethodImpl(MethodImplOptions.Synchronized)]
public Boolean Check()
{
if(quantity>buyQuantity)
{
decreaseQuantity(buyQuantity);
}
}
Hits: 2588
Comments (1)Add Comment
August 29, 2009     
...
can we also synchronize methods from remote places, that is mutiple client object
help
urt | 124.43.209.197

Write comment

busy
 

Sponsored Links

My friends

Bookingpoint
partner websites

Donate

Do you find content useful? Please donate so I can cover my hosting expenses! Thanks!