Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. safely end a thread

safely end a thread

Scheduled Pinned Locked Moved C#
question
9 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Y Offline
    Y Offline
    Yustme
    wrote on last edited by
    #1

    Hi, I'm trying to end 3 threads in a save way. I can get 2 threads to stop, but the last one doesn't seem to abort. My try:

    // Volatile is used as hint to the compiler that this data
    // member will be accessed by multiple threads.
    private volatile bool stopRequested = false;

    this.stopRequested = true;

    // Use the Join method to block the current thread
    // until the object's thread terminates.
    this.thdPageContent1.Join();

    this.thdPageContent2.Join();

    this.thdFileComparer.Join();

    After the thdFileComparer thread, i got a messagebox that 'tells' me the threads are stopped: MessageBox.Show("Threads stopped successfully"); Any idea what I might be doing wrong? Thanks in advance!

    P L 2 Replies Last reply
    0
    • Y Yustme

      Hi, I'm trying to end 3 threads in a save way. I can get 2 threads to stop, but the last one doesn't seem to abort. My try:

      // Volatile is used as hint to the compiler that this data
      // member will be accessed by multiple threads.
      private volatile bool stopRequested = false;

      this.stopRequested = true;

      // Use the Join method to block the current thread
      // until the object's thread terminates.
      this.thdPageContent1.Join();

      this.thdPageContent2.Join();

      this.thdFileComparer.Join();

      After the thdFileComparer thread, i got a messagebox that 'tells' me the threads are stopped: MessageBox.Show("Threads stopped successfully"); Any idea what I might be doing wrong? Thanks in advance!

      P Offline
      P Offline
      Paulo Zemek
      wrote on last edited by
      #2

      The join method only waits for a thread to end... it does not abort the thread. So, if your thread is in an infinite loop (or infinite wait), your join will be waiting infinitelly. I must say I need to know the thread code to know what's wrong... but, if you are using some event (ManualResetEvent, for example) in the 3rd thread, you must set it. So, the thread can execute (and check the stopRequested variable).

      Y 1 Reply Last reply
      0
      • Y Yustme

        Hi, I'm trying to end 3 threads in a save way. I can get 2 threads to stop, but the last one doesn't seem to abort. My try:

        // Volatile is used as hint to the compiler that this data
        // member will be accessed by multiple threads.
        private volatile bool stopRequested = false;

        this.stopRequested = true;

        // Use the Join method to block the current thread
        // until the object's thread terminates.
        this.thdPageContent1.Join();

        this.thdPageContent2.Join();

        this.thdFileComparer.Join();

        After the thdFileComparer thread, i got a messagebox that 'tells' me the threads are stopped: MessageBox.Show("Threads stopped successfully"); Any idea what I might be doing wrong? Thanks in advance!

        L Offline
        L Offline
        Luc Pattyn
        wrote on last edited by
        #3

        Yustme wrote:

        the last one doesn't seem to abort

        Aborting a thread is a bad idea as it leaves things in an unknown state. But then maybe you're not really calling Thread.Abort() at all?

        Yustme wrote:

        this.stopRequested = true;

        This doesn't do anything, unless your thread is periodically checking that variable. But then you did not show such code, making me doubt you understand how your code is working. :|

        Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


        I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
        All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


        Y 1 Reply Last reply
        0
        • P Paulo Zemek

          The join method only waits for a thread to end... it does not abort the thread. So, if your thread is in an infinite loop (or infinite wait), your join will be waiting infinitelly. I must say I need to know the thread code to know what's wrong... but, if you are using some event (ManualResetEvent, for example) in the 3rd thread, you must set it. So, the thread can execute (and check the stopRequested variable).

          Y Offline
          Y Offline
          Yustme
          wrote on last edited by
          #4

          Hi, What do I need to do to end the thread after the Join? The 3rd thread has a while loop and in side that while loop i got a nested for statement. One for statement in another one. I check for the volatile variable in my while loop. And once more inside the deepest for statement. That should be enough right?

          P 1 Reply Last reply
          0
          • Y Yustme

            Hi, What do I need to do to end the thread after the Join? The 3rd thread has a while loop and in side that while loop i got a nested for statement. One for statement in another one. I check for the volatile variable in my while loop. And once more inside the deepest for statement. That should be enough right?

            P Offline
            P Offline
            Paulo Zemek
            wrote on last edited by
            #5

            If you check the variable, it should end. Are you sure there is nothing more happening? Can't you put a break point in the last join and, instead of executing it, as all threads are stopped, check what's happening in the other thread? Maybe put some breakpoints at that moment and then allow the Join to go... you must see exactly what the other thread is doing.

            Y 1 Reply Last reply
            0
            • P Paulo Zemek

              If you check the variable, it should end. Are you sure there is nothing more happening? Can't you put a break point in the last join and, instead of executing it, as all threads are stopped, check what's happening in the other thread? Maybe put some breakpoints at that moment and then allow the Join to go... you must see exactly what the other thread is doing.

              Y Offline
              Y Offline
              Yustme
              wrote on last edited by
              #6

              Yes I'm sure. The variable gets checked alright. But it doesn't seem to stop it. Here is that thread i'm talking about with the code:

              private void FileComparerThread()
              {

              		while (this.stopRequested != true)
              		{
              
              			for (int i = 0; i < Directory.GetFiles(this.dest).Length; i++)
              			{
              				string\[\] filePaths = Directory.GetFiles(this.dest, "\*.txt");
              
              				for (int j = 0; j < filePaths.Length; j++)
              				{ // check if btnCancel has been pressed if so, end this thread.
              					if (this.stopRequested != true)
              					{
              						// check if file names are not the same:
              						if (filePaths\[i\].ToString() != filePaths\[j\].ToString())
              						{
              							bool comparedFiles = this.FileCompare(filePaths\[i\].ToString(), filePaths\[j\].ToString());
              
              							// move 1 file if they are both the same to another directory
              							if (comparedFiles)
              								Directory.Move(filePaths\[j\], Path.Combine(this.dest2, Path.GetFileName(filePaths\[j\])));
              						}
              					}
              
              				}
              				
              				if(filePaths.Length > 3)
              					File.Move(filePaths\[i\], Path.Combine(this.dest, Path.GetFileName(filePaths\[i\])));
              				
              				Thread.Sleep(5000);
              			}
              		}
              	}
              

              And then I got a this.FileCompare() function that checks 2 files for equality thats it. I've done some big time debugging. Its just looping those for statements. Even though the stopRequested = true. It's not comming out that for statement.

              P 1 Reply Last reply
              0
              • L Luc Pattyn

                Yustme wrote:

                the last one doesn't seem to abort

                Aborting a thread is a bad idea as it leaves things in an unknown state. But then maybe you're not really calling Thread.Abort() at all?

                Yustme wrote:

                this.stopRequested = true;

                This doesn't do anything, unless your thread is periodically checking that variable. But then you did not show such code, making me doubt you understand how your code is working. :|

                Luc Pattyn [Forum Guidelines] [Why QA sucks] [My Articles]


                I only read code that is properly formatted, adding PRE tags is the easiest way to obtain that.
                All Toronto weekends should be extremely wet until we get it automated in regular forums, not just QA.


                Y Offline
                Y Offline
                Yustme
                wrote on last edited by
                #7

                Hi, I didn't abort the thread. That was just 'speaking'. I know, i check its state on different places periodically. The code has grown too big to post it. I've reduced it now. I didn't see your post yesterday!

                1 Reply Last reply
                0
                • Y Yustme

                  Yes I'm sure. The variable gets checked alright. But it doesn't seem to stop it. Here is that thread i'm talking about with the code:

                  private void FileComparerThread()
                  {

                  		while (this.stopRequested != true)
                  		{
                  
                  			for (int i = 0; i < Directory.GetFiles(this.dest).Length; i++)
                  			{
                  				string\[\] filePaths = Directory.GetFiles(this.dest, "\*.txt");
                  
                  				for (int j = 0; j < filePaths.Length; j++)
                  				{ // check if btnCancel has been pressed if so, end this thread.
                  					if (this.stopRequested != true)
                  					{
                  						// check if file names are not the same:
                  						if (filePaths\[i\].ToString() != filePaths\[j\].ToString())
                  						{
                  							bool comparedFiles = this.FileCompare(filePaths\[i\].ToString(), filePaths\[j\].ToString());
                  
                  							// move 1 file if they are both the same to another directory
                  							if (comparedFiles)
                  								Directory.Move(filePaths\[j\], Path.Combine(this.dest2, Path.GetFileName(filePaths\[j\])));
                  						}
                  					}
                  
                  				}
                  				
                  				if(filePaths.Length > 3)
                  					File.Move(filePaths\[i\], Path.Combine(this.dest, Path.GetFileName(filePaths\[i\])));
                  				
                  				Thread.Sleep(5000);
                  			}
                  		}
                  	}
                  

                  And then I got a this.FileCompare() function that checks 2 files for equality thats it. I've done some big time debugging. Its just looping those for statements. Even though the stopRequested = true. It's not comming out that for statement.

                  P Offline
                  P Offline
                  Paulo Zemek
                  wrote on last edited by
                  #8

                  I think I know what's the problem. You didn't return in the internal if. So, stopRequested is true. Your method does not compare the files, but continue in it's loop, waits for 5 seconds and so on. So, I think instead of:

                  if (this.stopRequested != true)
                  {
                  ... some code...
                  }

                  You should use:

                  if (stopRequested)
                  return;

                  Y 1 Reply Last reply
                  0
                  • P Paulo Zemek

                    I think I know what's the problem. You didn't return in the internal if. So, stopRequested is true. Your method does not compare the files, but continue in it's loop, waits for 5 seconds and so on. So, I think instead of:

                    if (this.stopRequested != true)
                    {
                    ... some code...
                    }

                    You should use:

                    if (stopRequested)
                    return;

                    Y Offline
                    Y Offline
                    Yustme
                    wrote on last edited by
                    #9

                    Hi, You're right, About an hour ago i got an else statement after that if-statement with a return. I'll use your suggestion. Saves me some line of codes :P Thanks!

                    1 Reply Last reply
                    0
                    Reply
                    • Reply as topic
                    Log in to reply
                    • Oldest to Newest
                    • Newest to Oldest
                    • Most Votes


                    • Login

                    • Don't have an account? Register

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • World
                    • Users
                    • Groups