Break from thread

koteswara rao

Member
Joined
Feb 1, 2022
Messages
12
Programming Experience
3-5
Hi all, Thanks in advance
I am running one thread from start button click. that thread is in the while loop .I am trying to give the break for the while loop in the Abort Button click. but its not giving the break please help me in this task.


run the code from start click

Startclick:
 ThreadForStartTest = new Thread(new ThreadStart(Method_containingwithWhileLoop));
                ThreadForStartTest.IsBackground = true;
                ThreadForStartTest.Start();
                TmrForFullTest.Start();


Abort Button click:
 private void Cntrl_BtnAbort_Click(object sender, EventArgs e)
        {           
          
            if (ThreadForStartTest != null && ThreadForStartTest.IsAlive)
            {
                try
                {
                    ThreadForStartTest.Join(100);
                    FlagforAbortClicked = true;
              
                  
                }
                catch (Exception ex)
                {
                
                }
            }
        }
 
Your thread needs to poll a flag to see if it needs stop running. Your abort button should then set that flag to true, and then do as you are doing and call Join() if you are guaranteed that the thread will respond in less than 300 milliseconds. If no such guarantee exists, then you'll likely need to have a timer which checks to see if the thread has stopped.
 
Basically, swap your lines 8 and 9.
 
I tried the that one also
I tried with
Parallel:
 Parallel.Invoke(
                
            )
and
Task:
Task task1 = Task.Run(() => { Method_containingwithWhileLoop(); });

Not working
can you suggest me the sample code.
 
Show us the code for the method containing the while loop.
 
code:
 public async  void Method_containingwithWhileLoop()  //Another Try for continues reading withut Trigger
        {
            //Logic For Rotation Angle as per States.//           
            while (true)
            {
                Task.Delay(20).Wait(); ;
               Thread.Sleep(20);
                if (FlagforAbortClicked == false)
                    {
                      
                        double angle = CheckforValueonPositioner();
                        compassCard1.RotateAngle = (float)angle + 180;
                    //check the angle and rotate the positioner
                        //compassCard1.RotateAngle = angle;
                        //if (RunningPinPositionValue <= 180)
                        //    Cntrl_txtDialangle.Text = ((int)(-(180 - CheckforValueonPositioner()))).ToString();
                        //else
                        //    Cntrl_txtDialangle.Text = ((int)(CheckforValueonPositioner() - 180)).ToString();
                        Statustbyte = mbSession.ReadStatusByte();

                        switch (Casees)
                        {
                            case 0:
                                if (flagForCheckCometoZero == 0)
                                {
                                    //if (angle < -179.98 || angle > 179.98)//when start buttun clicks case is 0 when the angle is below -179.98 will clear the all the list of variable and gives the fwd command next goes to case 1
                                    if (((int)Statustbyte) == 0x58)
                                    {
                                        flagForCheckCometoZero++;
                                        InterpolitionanglesCh1.Clear(); InterpolitionVNAValuesCh1.Clear();
                                        InterpolitionanglesCh2.Clear(); InterpolitionVNAValuesCh2.Clear();
                                        InterpolitionanglesCh3.Clear(); InterpolitionVNAValuesCh3.Clear();
                                        InterpolitionanglesCh4.Clear(); InterpolitionVNAValuesCh4.Clear();
                                        textToWrite = "HLAa3<Ae0<MT<Daf<Va" + VelocityStr(Cntrl_TxtVelocity.Text) + "<Pat" + "17999" + "<\r\n";
                                        WriteCommandToPositioner(textToWrite);
                                        textToWrite = "G\r\n";
                                        WriteCommandToPositioner(textToWrite);
                                        Thread.Sleep(20);
                                        Casees = 1;
                                    }
                                }

                                break;
                            case 1:


                                if (((int)Statustbyte) == 0x58)  //if its 120  if its 179.99 it will be true and add the mesured values to Interpolitin values next gives the reverse direction command goes to case 2
                                                                 // if (Convert.ToDouble(RecivedValueArrangemets(responseString)) < 179.99 && Convert.ToDouble(RecivedValueArrangemets(responseString)) > -179.99)
                                {

                                    //foreach (int Closestto in FixedArrayforANgles)
                                    //{
                                    //    double ClosestValue = ClosestTo(InterpolitionanglesCh1, Closestto);
                                    //    int indexofClosestValue = Array.IndexOf(InterpolitionanglesCh1.ToArray(), ClosestValue);
                                    //    InterpolitionVNAValuesCh1forTAAP.Add(InterpolitionVNAValuesCh1[indexofClosestValue]);
                                    //    InterpolitionVNAValuesCh2forTAAP.Add(InterpolitionVNAValuesCh2[indexofClosestValue]);
                                    //    InterpolitionVNAValuesCh3forTAAP.Add(InterpolitionVNAValuesCh3[indexofClosestValue]);
                                    //    InterpolitionVNAValuesCh4forTAAP.Add(InterpolitionVNAValuesCh4[indexofClosestValue]);
                                    //}
                                    textToWrite = "HLAa3<Ae0<MT<Dar<Va" + VelocityStr(Cntrl_TxtVelocity.Text) + "<Pat" + "18001" + "<\r\n";
                                    WriteCommandToPositioner(textToWrite);
                                    textToWrite = "G\r\n";
                                    WriteCommandToPositioner(textToWrite);
                                    Casees = 2;
                                }
                                else
                                {//then it will come hear and measure
                                    InterpolitionanglesCh1.Add((float)angle);
                                    StrData1 = vNA.VNA_WriteAndRead(VNA_SCPICommandsList.MarkerDataread_1);
                                    OutData1 = vNA.StringtoStringArray(StrData1);
                                    StrData2 = vNA.VNA_WriteAndRead(VNA_SCPICommandsList.MarkerDataread_2);
                                    OutData2 = vNA.StringtoStringArray(StrData2);
                                    StrData3 = vNA.VNA_WriteAndRead(VNA_SCPICommandsList.MarkerDataread_3);
                                    OutData3 = vNA.StringtoStringArray(StrData3);
                                    StrData4 = vNA.VNA_WriteAndRead(VNA_SCPICommandsList.MarkerDataread_4);
                                    OutData4 = vNA.StringtoStringArray(StrData4);
                                    InterpolitionVNAValuesCh1.Add(Convert.ToDouble(OutData1[0]));
                                    InterpolitionVNAValuesCh2.Add(Convert.ToDouble(OutData2[0]));
                                    InterpolitionVNAValuesCh3.Add(Convert.ToDouble(OutData3[0]));
                                    InterpolitionVNAValuesCh4.Add(Convert.ToDouble(OutData4[0]));



                                    if (TmrrepeetFlag == 5)
                                    {
                                        XVal_J1.Add((float)angle);
                                        XVal_J2.Add((float)angle);
                                        XVal_J3.Add((float)angle);
                                        XVal_J4.Add((float)angle);
                                        YVal_J1.Add(Convert.ToDouble(OutData1[0]));
                                        YVal_J2.Add(Convert.ToDouble(OutData2[0]));
                                        YVal_J3.Add(Convert.ToDouble(OutData3[0]));
                                        YVal_J4.Add(Convert.ToDouble(OutData4[0]));

                                    }
                                    else if (TmrrepeetFlag == 1)
                                    {
                                        XVal_J1.Add((float)angle);
                                        YVal_J1.Add(Convert.ToDouble(OutData1[0]));
                                    }
                                    else if (TmrrepeetFlag == 2)
                                    {
                                        XVal_J2.Add((float)angle);
                                        YVal_J2.Add(Convert.ToDouble(OutData2[0]));
                                    }
                                    else if (TmrrepeetFlag == 3)
                                    {
                                        XVal_J3.Add((float)angle);
                                        YVal_J3.Add(Convert.ToDouble(OutData3[0]));

                                    }
                                    else if (TmrrepeetFlag == 4)
                                    {
                                        XVal_J4.Add((float)angle);
                                        YVal_J4.Add(Convert.ToDouble(OutData4[0]));
                                    }
                                }

                                break;
                            case 2: //measure the reverse values
                                if (((int)Statustbyte) == 0x58)
                                {
                                    ThreadForStartTest.Abort();
                                }
                                else
                                {
                                    if (TmrrepeetFlag == 5)
                                    {

                                        XVal_J1_Rev.Add((float)angle);
                                        XVal_J2_Rev.Add((float)angle);
                                        XVal_J3_Rev.Add((float)angle);
                                        XVal_J4_Rev.Add((float)angle);
                                        YVal_J1_Rev.Add(Convert.ToDouble(OutData1[0]));
                                        YVal_J2_Rev.Add(Convert.ToDouble(OutData2[0]));
                                        YVal_J3_Rev.Add(Convert.ToDouble(OutData3[0]));
                                        YVal_J4_Rev.Add(Convert.ToDouble(OutData4[0]));

                                    }
                                    else if (TmrrepeetFlag == 1)
                                    {
                                        XVal_J1_Rev.Add((float)angle);
                                        YVal_J1_Rev.Add(Convert.ToDouble(OutData1[0]));
                                    }
                                    else if (TmrrepeetFlag == 2)
                                    {
                                        XVal_J2_Rev.Add((float)angle);
                                        YVal_J2_Rev.Add(Convert.ToDouble(OutData2[0]));
                                    }
                                    else if (TmrrepeetFlag == 3)
                                    {
                                        XVal_J3_Rev.Add((float)angle);
                                        YVal_J3_Rev.Add(Convert.ToDouble(OutData3[0]));
                                    }
                                    else if (TmrrepeetFlag == 4)
                                    {
                                        XVal_J4_Rev.Add((float)angle);
                                        YVal_J4_Rev.Add(Convert.ToDouble(OutData4[0]));
                                    }
                                }
                                break;
                                //Commandtosend += "Pat" + MODEL.HelperMethods.DataBitsAllocate(RunningPinPositionValue.ToString(), 3) + "00<" + Environment.NewLine;
                                //  ChekForVNAAppruning();


                        }
                    }
                    else
                    {
                        DialogResult dialogResult = MessageBox.Show("Do you want the positione to go back to the start position?", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        if (dialogResult == DialogResult.Yes)
                        {
                            String Commmand_StopAll = "H";
                            PrintPositionarSendCommands(Commmand_StopAll);
                            textToWrite = "HLAa3<Ae0<MT<Dar<Va" + VelocityStr(Cntrl_TxtVelocity.Text) + "<Pat" + "18001" + "<\r\n";
                            WriteCommandToPositioner(textToWrite);
                            textToWrite = "G\r\n";
                            WriteCommandToPositioner(textToWrite);
                            DemoTimer.Enabled = false;
                            Cntrl_BtnFullTest.Enabled = true;
                            Cntrl_Ports.Enabled = true;
                            Cntrl_BtnJ1.Enabled = true;
                            Cntrl_BtnJ2.Enabled = true;
                            Cntrl_BtnJ3.Enabled = true;
                            Cntrl_BtnJ4.Enabled = true;

                        }
                        else
                        {

                            String Commmand_StopAll = "H";
                            PrintPositionarSendCommands(Commmand_StopAll);
                            DemoTimer.Enabled = false;
                            Cntrl_BtnFullTest.Enabled = true;
                            Cntrl_Ports.Enabled = true;
                            Cntrl_BtnJ1.Enabled = true;
                            Cntrl_BtnJ2.Enabled = true;
                            Cntrl_BtnJ3.Enabled = true;
                            Cntrl_BtnJ4.Enabled = true;
                        }
                        FlagforAbortClicked = true;
                        
                    }
              
                }
                
        }
 
Quick tip, C# shouldn't be written like old fashioned C where you have functions that run 200-300 lines long. You should keep C# methods under 50 lines to make things easier to understand by having everything visible within a screen. Use helper methods.

As an aside, the reason why C used to have long functions was that there was a performance gain by not having to make another function call on older processors and memory buses. That has long since changed with modern CPU and memory architectures as well as better compiler automatic inlining optimizations. Modern C now also recommends shorter functions to help out the programmer, rather than the long functions to help out the computer.
 
Anyway, so are you saying that you are not seeing message box being displayed by line 170?
 
Anyway, your lines 170-201 won't do anything to break out of the while(true) block that you have spanning lines 5-205. So even if you set the flag to true, the loop will still continue to run infinitely.

Also as an aside, calling Thread.Abort() is a really bad idea. It should only be called in extreme measures. Breaking out of a loop is not an extreme measure.
 

Latest posts

Back
Top Bottom