Reputation: 42440
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.
Upvotes: 4
Views: 322
Reputation: 2789
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?
Upvotes: 3
Reputation: 25495
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.
Upvotes: 3
Reputation: 1275
You don't need to call Abort, as the thread will be automatically stopped when NotifyIfNecessary ends.
Upvotes: 3
Reputation: 30155
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."
Upvotes: 4
Reputation: 112795
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.
Upvotes: 6