Application["TotalPlayings"]++ doesn't work

F

farmer

Compiler Error Message: CS0201: Only assignment, call, increment,
decrement, and new object expressions can be used as a statement

And:
(int)Application["TotalPlayings"]++;
Makes no sense.
 
G

Guest

int iCount = ((int)Application["TotalPlayings"])++;
Response.Write("count = " + iCount); //makes sense :)
 
S

Scott Allen

It would be faster (and safer) to declare a static int field in some
class (Global.asax, perhaps), and use Interlocked.Increment to be
thread safe.
 
F

farmer

Couldn't understand very much.Instead "Application[""]" with "static
int"?Sound very well,but how to use it in other pages?
 
H

Hans Kesting

Compiler Error Message: CS0201: Only assignment, call, increment,
decrement, and new object expressions can be used as a statement

And:
(int)Application["TotalPlayings"]++;
Makes no sense.

Application["TotalPlayings"] returns an object,
(int)Application["TotalPlayings"] unboxes that object and returns
an int as a *copy* of that value,
When you use the "++" operator, you will use that on that copy,
not on the original. So the original Application["TotalPlayings"] is
not updated.
Plus you might have a precedence problem: what would be evaluated
first: the (int) or the ++?

Hans Kesting
 
G

Guest

//http://msdn.microsoft.com/library/d...html/7b41355f-5050-4b2b-ac1c-d10dc206b46a.asp
Application.Lock();
if (Application["hitCount"] == null)
{
Application["hitCount"] = 1;
}
else
{

Application["hitCount"]= ((int)Application["hitCount"])+1;

}
Application.UnLock();

if (Application["hitCount2"] == null)
{
Application["hitCount2"] = 1;
}
else
{
//use Interlocked.Increment Method (thanks to Scott Allen for introducing
the idea)
//http://msdn.microsoft.com/library/d...frlrfsystemthreadinginterlockedclasstopic.asp
int iCount2 = (int)Application["hitCount2"];
Application["hitCount2"]=Interlocked.Increment(ref iCount2);
}
Response.Write ("Application count= " + Application["hitCount"]);
Response.Write ("Application count2= " + Application["hitCount2"]);
//How many programmers does it take to increment an application variable? :)
 
S

Scott Allen

It would look like:

using System.Threading;

public class HitCounter
{
static int _counter;

public static int IncrementCounter()
{
return Interlocked.Increment(ref _counter);
}

public static int GetCounter()
{
return _counter;
}
}

You could use it like:

int x = HitCounter.IncrementCounter();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,008
Latest member
HaroldDark

Latest Threads

Top