Summit
Summit

Reputation: 2268

How to stop a thread when application is closed

I am spawning a thread in the Form_load method and would like to close this thread when the application is closed.

private void Form1_Load(object sender, EventArgs e)
        {

          new Thread(() =>
            {             
            try
            {
                // Set the TcpListener on port 6101.
                Int32 port = 6101;
                IPAddress localAddr = IPAddress.Parse("127.0.0.1");

                // TcpListener server = new TcpListener(port);
                server = new TcpListener(localAddr, port);

                // Start listening for client requests.
                server.Start();

                // Buffer for reading data
                Byte[] bytes = new Byte[256];
                String data = null;

                // Enter the listening loop.
                while (isServerRun)
                {
               //     Console.Write("Waiting for a connection... ");

                    // Perform a blocking call to accept requests.
                    // You could also use server.AcceptSocket() here.
                    TcpClient client = server.AcceptTcpClient();
             //       Console.WriteLine("Connected!");

                    data = null;

                    // Get a stream object for reading and writing
                    NetworkStream stream = client.GetStream();

                    int i;

                    // Loop to receive all the data sent by the client.
                    while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
                    {
                        // Translate data bytes to a ASCII string.
                        data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
             

                        ReceiveCommand(data);

                        // Process the data sent by the client.
                        data = data.ToUpper();

                        byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);

                        // Send back a response.
                        stream.Write(msg, 0, msg.Length);
            
                    }

                    // Shutdown and end connection
                    client.Close();
                }

                MessageBox.Show("STOPPING");
                server.Stop();

            }
            catch (SocketException ett)
            {
                
            }
            finally
            {
                // Stop listening for new clients.
                server.Stop();
            }


        }).Start();
    }

        }

For that i am setting a variable to false and the loop in the spawned function should exit.

 private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {         
            isServerRun = false;  // with isServerRun as false the while
        }

loop should quit in the spawned thread function.

But still the Spawned thread does not quit

Upvotes: 0

Views: 243

Answers (1)

Onur Aksoy
Onur Aksoy

Reputation: 25

static bool isCancellation = false;
static object gateway = new object();

lock (gateway)
{
    isCancellation = true;
}

for (int i = 0; i < 1000; i++)
{
    Thread.SpinWait(5000000);

    lock (gateway)
    {
        if (isCancellation)
        {
            break;
        }
    }
}

Upvotes: 1

Related Questions