1

In one of my server application I have a class that look like,

class A
{
 static int _value = 0;
 void DoSomething()
 {
 // a request start here
 _value = 0;
 _value++;
 // a request end here
 }
 // This method can be called many time during request
 void SomeAsyncMethods()
 {
 _value++;
 }
}

The problem is SomeAsyncMethods is async. Can be called many times. What I need when a request start set _value = 0 and then asynchrosnously increment this. After end of request I need the total. But the problem is that another request at the same time can access the class.

asked Dec 10, 2012 at 12:49

1 Answer 1

4

use

System.Threading.Interlocked.Increment( ref _value );

instead of

_value++;

Interlocked.Increment

If multiple requests share this class and each one should get its own counter you need a non static counter that you pass to all threads working on this request.

Like this

class A
{
 void DoSomething()
 {
 // a request start here
 RequestData data = new RequestData();
 request.IncrementValue();
 // a request end here
 }
 // This method can be called many time during request
 void SomeAsyncMethods( RequestData request )
 {
 request.IncrementValue();
 }
}
class RequestData
{
 int _value = 0;
 public void IncrementValue()
 {
 System.Threading.Interlocked.Increment( ref _value );
 }
}
answered Dec 10, 2012 at 12:54
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.