So, as part of an assignment I am trying to roughly calculate the time taken for a transaction to be reviewed and completed in an ASP.NET Web Forms project using CSharp.
In my ASPX page, I am showing the details of the objects in the cart.
And there is a button which confirms the checkout and completes it.
What I need to calculate is the time since the page loaded, till the checkout was confirmed.
Here there are two events: page_load
and checkoutbutton_click
So in the code behind file I am
public partial class CheckoutReview : System.Web.UI.Page
{
public Stopwatch sw = new Stopwatch();
protected void Page_Load(object sender, EventArgs e)
{
sw.Start();
//... code
}
protected void checkoutbutton_click(object sender, EventArgs e)
{
//...code
sw.Stop();
// in the database i am then storing the elapsedMilliSeconds of the stopwatch
}
The problem however is that with this code the elapsed time is remained 0 all the time.
If I put the same stopwatch however in the checkoutbutton_click()
the stopwatch
works fine.
Can someone kindly explain what I am doing wrong here?
Each time the page is posted back to the server, a new instance of the class CheckoutReview
is being created... so what you're seeing is the time between the creation of the class on the post-back and the event handler.
You have to remember that each request to the server (whether it's the original page request, or a post-back) is an individual call to the server. Things like Session
and ViewState
exist to allow you use data between those requests.
I would recommend you store the current time in the ViewState
of the page on the initial load, and then check the TimeSpan
difference in the event handler...
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Only store on first visit to the page
ViewState["pageLoadTime"] = DateTime.Now;
}
}
protected void checkoutbutton_click(object sender, EventArgs e)
{
TimeSpan diff = DateTime.Now - (DateTime)ViewState["pageLoadTime"];
}