locking an int
- From: Dan Holmes <dan.holmes@xxxxxxxxxxxxxx>
- Date: Mon, 05 Oct 2009 08:48:36 -0400
I have TCP code that is incrementing an int for each accept socket. I tried to use lock(int) for synchronization but that doesn't work. I have settled on declaring the int as volatile. Will that work? Based on what i read about volatile this could work.
This is a poor man's load balancing app. The clients contact with this app and this app is just going to round-robin through the actual doers of stuff.
using SNS = System.Net.Sockets;
private const int Initial_Buffer_Size = 65536;
private SNS.TcpListener listener = null;
//this is incremented before the execution that is why it is initialized to -1 instead of 0.
private volatile int nextServantIndex = -1;
private void DoAcceptTcpClientCallback(IAsyncResult ar)
SNS.TcpListener listener = (SNS.TcpListener)ar.AsyncState;
SNS.TcpClient clientSckt = listener.EndAcceptTcpClient(ar);
listener.BeginAcceptTcpClient(new AsyncCallback(DoAcceptTcpClientCallback), listener);
byte readbuffer = new byte[Initial_Buffer_Size];
SNS.NetworkStream ns = clientSckt.GetStream();
StringBuilder message = new StringBuilder();
int bytesread = ns.Read(readbuffer, 0, readbuffer.Length);
while (bytesread > 0)
message.Append(Encoding.UTF8.GetString(readbuffer, 0, bytesread));
bytesread = ns.Read(readbuffer, 0, readbuffer.Length);
if (message.Length > 0)
//lock the int. since this is async IO more than 1 IO could be at this point
//need to make sure that the variable only gets accessed in a serial manner.
//move to the next servant
if (++nextServantIndex >= Properties.Settings.Default.Servants.Count)
nextServantIndex = 0;
- Prev by Date: Re: Why not numeric overflows?
- Next by Date: Nice advanced Forms with graphics
- Previous by thread: Determining whether an applications has thrown some error ...
- Next by thread: Re: locking an int