开发者

How to lock a setter property for a thread

开发者 https://www.devze.com 2023-01-05 00:50 出处:网络
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.

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.


This code definitely needs some refactoring for a start - too many threads being spanwed, and all in a very narrow context!

Short answer:

The problem boils down to the fact that Connect function is not called at the times (or even order) you expect it to be, but rather only when the loop is finished.

Long answer:

This is fairly typical scenario of concurrency issues when trying to use instance-scoped variables/properties within functions. As far as I can tell, the issue with not getting the desired value for Port is nothing directly to do with locking per se. (It may be solved that way, but not very gracefully and not in the way you probably think.) Ultimately you cannot control how blocks of time are allocated to different threads on the processor level, so you don't know which functions get executed in what order. You also seem to be mixing principles of stateful and stateless (functional) design, which is bound to get you into trouble. Stick to one - preferably the latter in this case - and you'll have much more success.

So I hope I'm being harsh to be kind here in saying that it would likely be beneficial to read up a bit on multithreading - it's a hugely complex topic - and practice some of the common principles. Good luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消