private static variable is replace with latest value when accessing from different browser - c#

96 Views Asked by At

My web page is showing the details of selected student(using the studentid) in a gridview. I have put an updatepanel with timer for this gridview to auto refresh the data within an interval of time. But now the issue is when a user1 is seeing the details of student1 from his system. and another user2 is seeing the details of student2 from his system. when the timer executes the updatepanel , both the user is seeing the latest student (student2) details. In short, when same web page is used by multiple users at same time, it shows the student details of latest user selected.

I have set the student id as private static. Will it be individual for each browser? Or will it be the issue of updatepanel with timer?

     <asp:UpdatePanel runat="server" ID="UpdatePanel1" UpdateMode="Conditional">
        <ContentTemplate>
             <asp:Timer ID="Timer2" runat="server" Interval= "<%$appSettings:update_timer%>" OnTick="Timer1_Tick"></asp:Timer>
         <asp:GridView ID="gv_studentdetails" runat="server" AutoGenerateColumns="true"  Caption="Student Details" 
    CssClass="gridview_alter" >
   </asp:GridView>
        </ContentTemplate>
     <Triggers>
              <asp:AsyncPostBackTrigger ControlID="Timer2" EventName="Tick" />
          </Triggers>
      </asp:UpdatePanel>

In web.config file

 <add key="update_timer" value="30000"/>

Code behind:

private static int student_id;
  if (!IsPostBack)
        {
           student_id=Convert.ToInt32(Session["selected_studentID"]);
           BindGridview(student_id);
        }
  protected async void Timer1_Tick(object sender, EventArgs e)
    {
        BindGridview(student_id);
        UpdatePanel1A.Update();
    }

NB: This issue is happening when run the timer of updatepanel only. When manually reload the page it is not .

1

There are 1 best solutions below

0
Svetoslav Petkov On
private static int student_id;

The value will be the same within a single web-server. No matter the browser sessions. That is why both browsers start to see the last value for the server.

But whenever someone reloads the page it will set the private field to their won session's selected_studentID. So then all the browsers will get that value evenutally.

  if (!IsPostBack)
        {
           student_id=Convert.ToInt32(Session["selected_studentID"]);
           BindGridview(student_id);
        }

Note: Manipulating a static instance without lock, may cause an issue. You can read more here c# critical sections, lock