MAKE A METHOD ACCESSIBLE TO ONE USER AT A TIME

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C# 
C#
 798  View(s)
Ratings:
Rate this:

I have got a method that i want only one user can access at a time. I really don't know how to do this.

 

public static int add(int a, int b)

{

 int c = a+b;

 return c;

}

and I am calling this method when a user enters data into two text boxes and click the submit button on a asp.net webpage. I don't want other users access to be denied. They should be kept in some sort of queue and when method is finished serving one user next user should be served.

  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Make a method accessible to one user at a time

    Since you have a static method, you need static Object for locking.

     

    public class Calculator

    {

        private static System.Object lockThis = new System.Object();

     

        public static void Add(int a, int b)

        {  

            lock (lockThis)

            {

                return a+b;

            }

        }

     

    }

     lock means, that whenever a Thread accesses that method and it is not locked, it will lock it and run the code. If it is locked it will do nothing until it is unlocked.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!