4

I have the following code fragment from a project I'm working on:

public void Start()
      {
         Thread t = new Thread(NotifyIfNecessary);
         Threads.Add(t);
         t.Start();
         t.Abort());

      }

What I want is that thread 't' should execute the method NotifyIfNecessary and abort only after the method has completed execution. In my current code, t.Abort() gets called prematurely.

Ayush
  • 41,754
  • 51
  • 164
  • 239
  • 1
    Is there a reason why you're aborting the thread? The thread should automatically end after the method completes execution anyway. – Matt DeKrey Dec 09 '10 at 15:30
  • Yeah...it seems I missed the fact that the thread will abort itself after the method execution. Thanks. Since you all said the same, upvoted all and first answer will be best answer. Thanks again. – Ayush Dec 09 '10 at 15:32

5 Answers5

6

This is being caused because you're creating a new thread and starting it, then immediately killing it from the thread that you just created it in by calling the Thread.Abort() method. You don't need to do this; your thread will finish when NotifyIfNecessary has completed execution. Just remove the line t.Abort(); and your code should work properly.

Donut
  • 110,061
  • 20
  • 134
  • 146
  • +1 as the answer is totally correct, but I would add that if there is code beyond your current Abort() statement, or that is executed after this method is called, that requires the thread to have completed, you can wait for the thread to complete by calling t.Join() instead of t.Abort(). This is useful when you have to do something expensive, but don't need the results immediately so you can give it to a worker thread, do other things that don't depend on the result, then guarantee that the work was completed before you try to use any results. – KeithS Dec 09 '10 at 15:59
4

You should not be calling abort in the first place, since abort applies only to failed user code (run within a separate appdomain). In your case, simply allow NotifyIfNecessary to run-to-completion (i.e. do not call abort). Done.

But perhaps what you are really trying to do, is have your main thread not proceed until the NotifyIfNecessary is complete. If that is the case, then call Thread "Join."

Brent Arias
  • 29,277
  • 40
  • 133
  • 234
3

You don't need to call Abort, as the thread will be automatically stopped when NotifyIfNecessary ends.

Emidee
  • 1,245
  • 1
  • 14
  • 33
3

If you want NotifyIfNecessary to complete don't abort the thread. If you want the function to only continue after you complete NotifyIfNecessary use join or don't call the function in another thread.

rerun
  • 25,014
  • 6
  • 48
  • 78
3

I don't see the need for the call to Abort(). Once NotifyIsNeccessary is complete the thread will complete anyway. Are you looking to wait at the end of Start() until the thread is complete?

Damian
  • 2,709
  • 2
  • 29
  • 40