kumar chaudhari
kumar chaudhari

Reputation: 89

lock(object) in C#

I am developing a web page with asp.net using C#.

I have a code which is critical. I want only one user to access that section of code at a time.

I have used the following code

string doc_number = "";
try {
    lock (lock1) {

        doc_number = PostSalaryToSAP();

        // doc_number = "";
        if (doc_number.Length > 6) {
            this.Result.Text = "Posting Successful For Employee id '" + cbEmpID.SelectedItem.Text.ToString() + "' With Doc_number : " + doc_number;
            this.Result.ForeColor = System.Drawing.Color.Green;
            this.btnPost.Enabled = false;
            this.btnDelete.Enabled = false;
        } else {
            this.Result.Text = "Posting Failed ";
            this.Result.ForeColor = System.Drawing.Color.Green;
        }
    }
} catch (Exception ex1) {
    Result.Text = "Posting Unsuccessful ";
    Result.ForeColor = System.Drawing.Color.Green;
}

but with this code this results are not getting generated properly. Normally this line adds a single record to db table:

doc_number = PostSalaryToSAP();

But using this code it adds 2 rows. What is is the actual issue I am not able to understand? Please help

Upvotes: 0

Views: 718

Answers (1)

Myles McDonnell
Myles McDonnell

Reputation: 13335

Assuming that this is a single node application the object on which you lock must be of application scope. Remember that each page request creates a new instance of the page, so if lock1 is a member of that page then multiple requests will be able to execute the critical section concurrently. Create the lock object on the Global.asax OnApplicationStart > Application["SalaryPostLock"].

If however you will run the application in a cluster you will need a distributed locking mechanism. Please advise if this is the case?

Upvotes: 3

Related Questions