ThreadPools and termination

P

Peter Kirk

Hi there, I have a question regarding ThreadPools. Say I have the following
program, which has a timer which on every "tick" queues a method for
execution. This works ok (and up to 25 methods can be queued at a time - as
per documentation).

But, when the main application exits, then all the executing methods are
also terminated. How do I stop this? I mean, how do I ensure that when the
application is shut down the timer is stopped (so no more methods are
queued) and all the executing methods are allowed to finish before the
application actually exits?

Thanks, Peter.

using System;
using System.Threading;
using System.Timers;
namespace ConsoleApplication1
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine("Main START");
Class1 c = new Class1();
c.doIt();
Console.WriteLine("Main END - press enter to exit");
Console.Read();
}
public void doIt()
{
Console.WriteLine("doIt START");
System.Timers.Timer pollTimer = new System.Timers.Timer();
pollTimer.Elapsed += new ElapsedEventHandler(TimerElapsed);
pollTimer.Interval = 1000;
pollTimer.Enabled = true;
Console.WriteLine("doIt END");
}
private void TimerElapsed(object source, ElapsedEventArgs e)
{
QueueTagger();
}
private void QueueTagger()
{
if (ThreadPool.QueueUserWorkItem(new WaitCallback(Tag)))
{
Console.WriteLine("QueueTagger - queue ok");
}
else
{
Console.WriteLine("QueueTagger - queue failed");
}
}
private void Tag(object state)
{
try
{
Console.WriteLine("Tag START");
// do long work...
Thread.Sleep(80000);
Console.WriteLine("Tag END");
}
catch (Exception ex)
{
Console.WriteLine("Exception " + ex.Message);
}
}
}
}
 
I

Ignacio Machin \( .NET/ C# MVP \)

hi,

The threadpool will no prevent you application from end, for this you have
to create a Thread , and not set the IsBackground property (is false by
default )
this will prevent the app from ending.

Now to, stop the timer you can use the Application.ApplicationExit event to
stop it.

what kind of timer r u using?
it's a win app?


cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top