0

I show you my problem by simple code snippet.

This is popular scenario. Users load our page when there is no cache so we generate one. In my code example this take 120 seconds to save cache and before this i inrement static variable.

My qustion is why static variable "i" doesn't increment when i open this page many times in the same moment and cache is null.

public partial class _Default : Page
{
    static int i = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        int i;

        var cache = Cache.Get("cache") as string;
        if (string.IsNullOrEmpty(cache))
        {
            i = GenerateCache();
        }
        else
        {
            i = Convert.ToInt32(cache);
        }

        Response.Write(i.ToString());
    }

    public int GenerateCache()
    {
        var sw = new Stopwatch();
        sw.Start();

        ++i;

        Response.Write(i+"<br>");

        while (sw.ElapsedMilliseconds < 1000 * 120) { }

        Cache.Insert("cache", i.ToString());

        return i;
    }
}
Emil Jasiński
  • 391
  • 4
  • 13

1 Answers1

0

Because you have a bug by declaring again the i on the PageLoad

  protected void Page_Load(object sender, EventArgs e)
    {
        int i; // <----- here, this is probably bug and you must remove this line

also you need some kind of locking to avoid multiple calls at the same moment, even tho you saved by the lock of the page session for the moment.

Aristos
  • 66,005
  • 16
  • 114
  • 150
  • I didn't know what session lock is but this is answer. I wrote this code because i wanted test lock on the GenerateCache method and this was big suprise for me that code works like i want without it. The local variable "i" wasn't bug, imho. – Emil Jasiński Aug 31 '13 at 17:49
  • @user114265 read this answer to see what I am say about http://stackoverflow.com/questions/12284530/asp-net-server-does-not-process-pages-asynchronously/12285168#12285168 – Aristos Aug 31 '13 at 19:16
  • Yes, I understand now. If we open normal tab and incognito tab (chrome browser) we have diffrent sessions and value "i" is increment. – Emil Jasiński Aug 31 '13 at 20:59