I have the following code fragment from a project I'm working on:
public void Star开发者_如何学编程t()
{
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.
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.
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."
You don't need to call Abort, as the thread will be automatically stopped when NotifyIfNecessary ends.
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.
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?
精彩评论