¿Cómo iniciar el hilo si se presiona el botón y detenerlo si se presiona nuevamente?
Estoy usando el siguiente código para hacer lo que estoy pidiendo:
private delegate void CallerDelegate(object e);
CallerDelegate caler = new CallerDelegate(MethodToCall);
en el evento de clic de botón:
if (currBusyThrd != null && currBusyThrd.IsAlive)
{
currBusyThrd.Abort();
}
ThreadPool.SetMaxThreads(1, 1);
//queue the work for thread processing
ThreadPool.QueueUserWorkItem(new WaitCallback(WaitCallbackMethod))
El método "WaitCallbackMethod" es:
void WaitCallbackMethod(object stateInfo)
{
// argList : i put some argument in a list to use it in "MethodToCall" ...
BeginInvoke(caler,argList);
}
y el método que estoy llamando por el hilo es:
void MethodToCall(object args)
{
//Here I get the thread I'm calling to stop it when btn clicked again
currBusyThrd = Thread.CurrentThread;
// The rest of the code ...
}
Siento que esto está mal ... ¿Cómo hacerlo bien?
En realidad, la llamada se realizará mediante TextBox_KeyUp .. así que cada vez que el usuario ingresa un char, el código se ejecutará nuevamente ... y BackgroundWorker no funcionó.