I am running four threads that gets and sets the same property. When i uses breakpoint then it gives me result as expected but when i runs it directly it gives me last updated result.
Here is my code
int Port { get; set; }
Thread[] tMain= new Thread[4];
public void btnListen_Click(object sender, EventArgs e)
{
for (int i = 0; i < 4; i++)
{
tMain[i] = new Thread(Connect);
tMain[i].IsBackground = true;
tMain[i].Start(8000+i);
}
}
public void Connect(object _port)
{
try
{
lock ((object)Port)
{
Port = (int)_port;
}
IPEndPoint ie = new IPEndPoint(IPAddress.Any, Port);
Socket listenSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSock.Bind(ie);
listenSock.Listen(100);
Thread tListen = new Thread(() => StartListening(listenSock, Port));
tListen.IsBackground = true;
tListen.Start();
}
catch (SocketException ex)
{
MessageBox.Show(ex.Message);
}
}
public void StartListening(Socket _socket, int port)
{
Socket tempSock,listenerSocket=(Socket)_socket;
MessageBox.Show("Thread Started"+port.ToString());
while (true)
{
MessageBox.Show("Waiting For Connection");
tempSock = listenerSocket.Accept();
Thread tInner = new Thread(ProcessMessages);
tInner.IsBackground = true;
tInner.Start(tempSock);
}
}
Now what I see over here is when the code is executed i gets 8003 in all the message boxes. That's might be because first 3 thread could not modify the property in the meantime when it was accessed . How to get a lock in this case.