Stefan Candan
Stefan Candan

Reputation: 891

Thread stopping prematurely

Somehow my thread is stopping prematurely, while it should be alive all the time until the status becomes 4, or the thread is aborted through .Abort().

Currently this is how I start my thread:

var thread = new Thread(() =>
{
   var t = Thread.CurrentThread;
   var cDown = new cDownloader(textBox1, textBox3.Text, this, 10);
   updateThreads(t.ThreadState + ": " + t.Name, t);
 });
 thread.Start();

The thread executes several functions inside the cDownloader class:

  1. The constructor, cDownloader(), which sets several variables.
  2. The constructor fires initLoad(), which iniates a timer, and adds an event to it.
  3. The timer tick event scans a website with HtmlAgilityPack, for links with class fileThumb.
  4. For every link, the event creates a new thread that downloads the file.

Somehow the thread seems to activate everything, even downloading the files, and then closes itself, whilst still running the timer, which is weird, and thus it results in an error because the current thread can't be found.

Nowhere am I calling .Abort() method on the current thread.

So my question is: Why is my thread stopping prematurely?

Upvotes: 1

Views: 930

Answers (3)

3Dave
3Dave

Reputation: 29041

It doesn't look like anything inside the thread is actually blocking. You could use an exit flag, like so:

var exitRequested = false;

new Thread(
() => {
  var t = Thread.CurrentThread;
  var cDown = ...
  Name = textBox1.Text;
  updateThread(...);
  while(!exitRequested)
  {
    /// keep this thread from locking up a CPU core
    t.Sleep(10);
  }

}
).Start();

and, later on when you want the thread to exit (when the app is closing, an exit button is clicked, etc)

exitRequested=true;

The loop is necessary to keep the thread from exiting early. Otherwise, when it hits the end of your lambda, it returns just like any other method.

Also note that checking Thread.ThreadState within the thread will usually return ThreadState.Running, since in order for any code in the thread method to execute, the thread has to be running. ThreadState is useful outside of that context.

Upvotes: 3

JaredPar
JaredPar

Reputation: 754585

Part of the problem is the following line

Name = this.textBox1.Text;

The UI cannot be accessed from background threads and will throw an exception. Hence this line is throwing after the cDownloader class is created and subsequently kills the thread. You need to move the UI access out of the background thread or appropriately marshal access back to the UI thread.

Upvotes: 3

Brian Rasmussen
Brian Rasmussen

Reputation: 116401

The thread will run the code in the delegate you pass it. Once that is complete the thread will terminate. Unless updateThreads contains a loop, the thread will terminate upon completion of the last method call in the delegate.

Upvotes: 3

Related Questions