.NET 1.0 ThreadPool domanda
-
23-10-2019 - |
Domanda
Sto cercando di generare un filo di prendersi cura di compito DoWork che dovrebbe prendere meno di 3 secondi. All'interno DoWork la sua assunzione di 15 secondi. Voglio abortire DoWork e trasferire la parte posteriore di controllo per thread principale. Ho copiato il codice come segue e la sua non funziona. Invece di interrompere DoWork, termina ancora DoWork e quindi trasferisce il controllo posteriore di filo principale. Che cosa sto facendo di sbagliato?
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);
}
}
Soluzione
pool discussioni sono thread in background, nel senso che terminano automaticamente quando il thread in primo piano di applicazione (s) fine.
Ho cambiato il vostro ciclo e rimosso le resetEvents.
//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);
}
Altri suggerimenti
[STAThread]
è stato Singolo Thread Apartment. Prova [MTAThread]
che è Multi Discussione Appartamento.