Wednesday, May 6, 2020

How end threads in C#

I finally figure out how to; end threads in C#, it is not a CloseHandle(hThrd) neither Abort(). They[threads] end automatically when the control flow reach end of that thread.

Consider flowing code thing, on Visual Studio WinForm project. That has two threads and one main thread:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
//Those comes with WinForm this is new. 
using System.Threading;

namespace Test_that_new_Loop_thing
{
    public partial class Form1 : Form
    {
        bool lever = true;//when this is false a while-loop in place 28 stop
        public Form1()
        {
            //then some threads
            Thread thread1 = new Thread(new ThreadStart(Looppi_threadissa1)); // this is thread1 it run function that is inside it.
            Thread thread2 = new Thread(new ThreadStart(for_threadi2)); //these threads are in places 26 and 43
            InitializeComponent();
            thread2.Start();
            thread1.Start();
        }
        public void Looppi_threadissa1() {//26
            try {
                while (lever) //28
                {

                    Thread.Sleep(10);
                }

            }
            catch (Exception)
            {



            }
          
        }
        public void for_threadi2()//43
        {
            try {
                for (int i = 0; i < 1400; i++)
                {

                    Thread.Sleep(10);
                }
                lever = false;//lever turn false so while in pace 28 end.
                MessageBox.Show("Now the both threads end");

            }
            catch (Exception)
            {



            }
          

        }

    }
}

Yes see extra threads end when they end like main thread does too.

No comments:

Post a Comment

3D BLog has return

Go  to Check    https://thereal3dblog.com/