Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 886043
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T13:00:26+00:00 2026-05-15T13:00:26+00:00

I am running four threads that gets and sets the same property. When i

  • 0

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.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T13:00:27+00:00Added an answer on May 15, 2026 at 1:00 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Currently running a live e-commerce site that uses Hibernate 3.1 and JBoss Treecache in
I have to get a running total from four textboxes and have that total
We have four public websites running on the same database with different schema(Oracle). All
I have four divs each with the same ID but different class. <div id=inner
I'm working on problem four of Project Euler and am running into a stackoverflow
Running my script through Devel::NYTProf showed that the following portion of code took up
Running the following line in my script gives me a Permission denied error: $config_out
Running SQL Server 2008 (not R2). I have a few reports that have URLs
I have a web-app that has a master mysql db and four slave dbs.
I'm running Maven 3.0 and have cleared out my repository, then rebuilt the repository.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.