Pregunta de .NET 1.0 Threadpool
-
23-10-2019 - |
Pregunta
Estoy tratando de generar un hilo para cuidar la tarea de Dowork que debería tomar menos de 3 segundos. Dentro de Dowork está tomando 15 segundos. Quiero abortar Dowork y transferir el control de regreso al hilo principal. He copiado el código de la siguiente manera y no funciona. En lugar de abortar Dowork, todavía termina Dowork y luego transfiere el control al hilo principal. ¿Qué estoy haciendo mal?
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
private static System.Threading.ManualResetEvent[] resetEvents;
[STAThread]
static void Main(string[] args)
{
resetEvents = new ManualResetEvent[1];
int i = 0;
resetEvents[i] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork),(object)i);
Thread.CurrentThread.Name = "main thread";
Console.WriteLine("[{0}] waiting in the main method", Thread.CurrentThread.Name);
DateTime start = DateTime.Now;
DateTime end ;
TimeSpan span = DateTime.Now.Subtract(start);
//abort dowork method if it takes more than 3 seconds
//and transfer control to the main thread.
do
{
if (span.Seconds < 3)
WaitHandle.WaitAll(resetEvents);
else
resetEvents[0].Set();
end = DateTime.Now;
span = end.Subtract(start);
}while (span.Seconds < 2);
Console.WriteLine(span.Seconds);
Console.WriteLine("[{0}] all done in the main method",Thread.CurrentThread.Name);
Console.ReadLine();
}
static void DoWork(object o)
{
int index = (int)o;
Thread.CurrentThread.Name = "do work thread";
//simulate heavy duty work.
Thread.Sleep(15000);
//work is done..
resetEvents[index].Set();
Console.WriteLine("[{0}] do work finished",Thread.CurrentThread.Name);
}
}
Solución
Todos hilos agrupados son hilos de fondo, lo que significa que terminan automáticamente cuando terminan los hilos de primer plano de la aplicación.
Cambié tu bucle y eliminé los reseteventos.
//abort dowork method if it takes more than 3 seconds
//and transfer control to the main thread.
bool keepwaiting = true;
while (keepwaiting)
{
if (span.Seconds > 3)
{
keepwaiting = false;
}
end = DateTime.Now;
span = end.Subtract(start);
}
Otros consejos
[STAThread]
es apartamento de un solo hilo. Probar [MTAThread]
que es un apartamento de hilo múltiple.
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow