简体   繁体   中英

How can i make my code threadsafe in this Scenario?

I have an ASP.NET Webform application. I added a Ado.net Entity Data Model for my database which has a table named GatewayProviders . My table has 3 columns: Id(int), Description(string), GatewayType(int) . I added two methods in webform1.aspx.cs :

 public void update()
    {
        GatewayProvider gp = DB.GatewayProviders.Find(12);
        gp.Description = "pejman";

        DB.SaveChanges();
    }

    public void update2()
    {
        GatewayProvider gp = DB.GatewayProviders.Find(12);
        gp.Description = "nazraz";
        DB.SaveChanges();
    }

I created a button named Button1 to webform1.aspx and i added click-event for button like this :

  protected void Button1_Click(object sender, EventArgs e)
    {
        Thread th = new Thread(new ThreadStart(update));
        Thread th2 = new Thread(new ThreadStart(update2));
        th.Start();
        th2.Start();
    }

assume i publish this application on web, then two client as the same time click on the button, my application give them error!! how can i fix it?

how can i make my code threadsafe ?

You know basic ASP.NET? Here is the hint:

ASP.NET is request/Response/done. Click->Sends order to server -> processes -> sends HTML.

in the CLick handler you start threads. Once the handler ends - the HTML is sent, ASP.NET is finished.

In your case:

You start threads, but then the procesing ends before likely they execute. The exact error message likely has interesting info WHICH object is null ;)

You absolutely MUST wait for both threads to finish before ending the click handler, because THEN (once you end the click handler) the HTML is generated and sent to the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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