0

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

2
  • 3
    what is lock1? It would normally be: private static readonly object lock1 = new object(); Commented Feb 22, 2012 at 7:29
  • 3
    I think this has nothing to do with the lock statement? Your code is probably executed twice higher up the callstack. Commented Feb 22, 2012 at 7:29

1 Answer 1

3

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?

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.