How to stop/start thread?
I have a workerthread that takes a username and password from two input开发者_如何转开发boxes, but I want to stop it if username/password are blank.
I've tried to use the Suspend() method but intellisens tells me its outdated. How do i stop/start a thread?
I don't see why you need a thread to get the input, but you should stop a thread by returning from it whenever the job is done. You should not just kill it.
if(!validInput(username, password))
return; // et voila
Edit: If your trying to synchronize more threads (like suspend/resume or wait/notify in java), then this information from the msdn may be useful:
Thread.Suspend has been deprecated. Please use other classes in System.Threading, such as Monitor, Mutex, Event, and Semaphore, to synchronize Threads or protect resources. http://go.microsoft.com/fwlink/?linkid=14202
You can use the Thread.Abort()
method, but it can lead to inconsistent shared state due to terminating a thread violently. A better alternative is to use collaborative termination by using a CancellationToken
.
// Create a source on the manager side
var source = new CancellationTokenSource();
var token = source.Token;
var task = Task.Factory.StartNew(() =>
{
// Give the token to the worker thread.
// The worker thread can check if the token has been cancelled
if (token.IsCancellationRequested)
return;
// Not cancelled, do work
...
});
// On the manager thread, you can cancel the worker thread by cancelling the source
source.Cancel();
精彩评论