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.

有帮助吗?

解决方案

Msdn got good explanation, check documentation. Thread Synchronization

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;
        }
    }

}

That 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.

Edit: Edited code for your method.

其他提示

you will need a static object, and use the keyword lock.

private static object locker = new object();
public static int add(int a, int b)
{
     lock(locker) 
     {
         //do stuff
     }
}

Assuming this method is within a singleton object you will then need to synchronize the method

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top