C# 中的锁(对象)
我正在使用 C# 使用 asp.net 开发一个网页。
我有一个至关重要的代码。我希望一次只有一个用户访问该代码部分。
我使用了以下代码
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;
}
,但使用此代码无法正确生成结果。通常此行会向 db 表添加一条记录:
doc_number = PostSalaryToSAP();
但使用此代码会添加 2 行。我无法理解的实际问题是什么?请帮忙
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
假设这是一个单节点应用程序,您锁定的对象必须属于应用程序范围。请记住,每个页面请求都会创建该页面的一个新实例,因此如果 lock1 是该页面的成员,则多个请求将能够同时执行关键部分。在 Global.asax 上创建锁对象 OnApplicationStart >
应用程序[“SalaryPostLock”]
。然而,如果您将在集群中运行应用程序,您将需要分布式锁定机制。请问是这种情况吗?
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?