Reputation: 14148
I am trying to spawn a thread to take care of DoWork task that should take less than 3 seconds. Inside DoWork its taking 15 seconds. I want to abort DoWork and transfer the control back to main thread. I have copied the code as follows and its not working. Instead of aborting DoWork, it still finishes DoWork and then transfers the control back to main thread. What am I doing wrong?
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);
}
}
Upvotes: 2
Views: 167
Reputation: 8043
All pooled threads are background threads, meaning they terminate automatically when the application's foreground thread(s) end.
I changed your loop and removed the 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);
}
Upvotes: 1
Reputation: 6440
[STAThread]
is Single Thread Apartment. Try [MTAThread]
which is Multi Thread Apartment.
Upvotes: 0