简体   繁体   English

在C#中锁定(对象)

[英]lock(object) in C#

I am developing a web page with asp.net using C#. 我正在使用C#用asp.net开发一个网页。

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: 通常,此行向db表添加一条记录:

doc_number = PostSalaryToSAP();

But using this code it adds 2 rows. 但是使用此代码会添加2行。 What is is the actual issue I am not able to understand? 我无法理解的实际问题是什么? Please help 请帮忙

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. 请记住,每个页面请求都会创建该页面的新实例,因此,如果lock1是该页面的成员,则多个请求将能够同时执行关键部分。 Create the lock object on the Global.asax OnApplicationStart > Application["SalaryPostLock"] . 在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? 请告知是否是这种情况?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM