Reputation:
I have following property in asp.net in which I am storing value of savingamount in session.
private double SavingAmount
{
get
{
if (_priceSavingAmount == 0.0f)
_priceSavingAmount = (double)Session["Saving"];
return _priceSavingAmount;
}
set
{
_priceSavingAmount = value;
Session["Saving"] = _priceSavingAmount;
}
}
USAGE
SavingAmount=FromService();
The problem with current property is that I am not getting refresh value means when I am getting new value from FromService() it still showing old value
Upvotes: 1
Views: 3904
Reputation: 22456
As I understand your question, you want to update in the Session variable whenever the result of FromService changes. Unfortunately, the values that you store in Session memory cannot be updated in that way. You'd have to manually check for new return values of FromSession and update the Session variable manually.
To avoid misunderstandings:
SavingAmount=FromService();
Assigns the return value of FromService at the time that it is called. In order to do so, FromService is called and the return value is assigned to the property. It is basically equivalent as:
var temp = FromService();
SavingAmount = temp;
Just writing the code in one line does not change this behavior.
So what can you do to solve your requirement: I suspect you put the return value of FromService in a Session variable in order not to call FromService too often. Unfortunately, you'd have to evaluate FromService in order to check whether the return value has changed in comparison to the value that is stored in Session memory.
One approach would be to call FromService once for each request (but only if the value is really needed). This way, the value is updated for each request, but it is guaranteed that not more than one call to the service is done per Request (of course if the value does not change between requests, you'd have more service calls than if the value in the session would be updated "magically"). In order to do so, you can store the value in the Request Items collection:
private double SavingAmount
{
get
{
double priceSavingAmount;
// Add some synchronization if required
if (!HttpContext.Current.Items.Contains("Saving"))
{
priceSavingAmount = FromService();
HttpContext.Current.Items.Add("Saving", priceSavingAmount);
}
else
priceSavingAmount = (double)HttpContext.Current.Items("Saving");
return priceSavingAmount;
}
}
Upvotes: 2