pass by reference ,value doesnt change

  • Thread starter Thread starter Anil TG
  • Start date Start date
A

Anil TG

Hello,
Im dealing with a Client Server application with multiple Client support.
In that i'm using an integer for storing the number of clients..

On each Client connect i'm incrementing the value in a thread Safe manner like

Interlocked.Increment(ref m_ClientCount);
//Now its value is say 1 ,after increment

In this i have a class

Class ClientConnect
{
public int _clientConnect ;
public ClientConnect(ref int _clientconnect_F)
{
_clientConnect = _clientconnect_F;
}
public void change()
{
//Decrementing the value of clients..

interlocked.Decrement(ref _clientconnect_F);

//the value should have reduced from 1 to 0 rite???
}
}

im calling a thread like this to invoke the function change()

ClientConnect obj=new ClientConnect(ref m_ClientCount);
Thread CxnManager= new Thread(new ThreadStart(obj.change));
CxnManager.Start();

Now come to my problem..When i check the value of m_ClientCount after the
above operation it seem to have the same value 1.it never changes.i tried
with
_clientconnect_F--; also
instead of interlocked.Decrement(ref _clientconnect_F); inside the
change();
But no change.Since i'v passed the integer via reference ,if i make some
changes to the formal parameter it should be reflected in the actual
parameter also..rite?..
But here its not happening..Any idea?...
 
Sorry i'v made a mistake in the question..
Inside the Change function iv written like
Interlocked.Decrement(red _clientConnect_F);
But that was a mistake,Actually im trying to decrement the variable
_clientConnect instead of _clientConnect_F;

i must have written like
Interlocked.Decrement(red _clientConnect);

Please note that..
 
Anil TG said:
Sorry i'v made a mistake in the question..
Inside the Change function iv written like
Interlocked.Decrement(red _clientConnect_F);
But that was a mistake,Actually im trying to decrement the variable
_clientConnect instead of _clientConnect_F;

i must have written like
Interlocked.Decrement(red _clientConnect);

Please note that..

it will change the value of _clientConnect, but not of the caller's
_clientConnect_F. That's not how pass by reference works - all it means
is that *for the duration of that member* (the constructor, in this
case) changes to the parameter will be visible to the caller.
 
it will change the value of _clientConnect, but not of the caller's
Is there any other way to change the value of m_ClientCount by passing it to
a function like this...?.
"Jon Skeet [C# MVP]" wrote:
 
Anil TG said:
Is there any other way to change the value of m_ClientCount by passing it to
a function like this...?.

No. Well, not without creating an extra class which basically wraps an
integer.

Frankly, I'd find that behaviour confusing.
 
Back
Top