As it is clear from the title
I want remove automatically threads from threads list when thread jobs done.
like:
Thread thr;
if(thr.done)
{
threadlist.remove(thr);
}
As it is clear from the title
I want remove automatically threads from threads list when thread jobs done.
like:
Thread thr;
if(thr.done)
{
threadlist.remove(thr);
}
you can check if the thread is finished with IsAlive and call this function in a timer:
var _timer = new Timer();
_timer.Interval = 30*1000; // specify interval time as you want
_timer.Tick += new EventHandler(timer_Tick);
void timer_Tick(object sender, EventArgs e)
{
foreach (var thr in threadList)
{
if (!thr.IsAlive)
{
threadlist.Remove(thr);
}
}
}
_timer.Start();
A better solution is to use a try-finally block in thread to determine when it is finished processing. see this example:
private static int lastThreadID=0; //We assign an ID to each thread
protected static object _lock = new object();
var thread = new Thread((tID) =>
{
try
{
work();
}
finally
{
removeThread((int)tID );
}
});
lock (_lock)
{
threadlist.Add(Tuple.Create(++lastThreadID, thread));
}
thread.Start(lastThreadID);
Action work = () =>
{
for (int i = 0; i < 20; i++)
Thread.Sleep(1000);
};
private static void removeThread(int tID)
{
lock (_lock)
{
threadlist.RemoveAll((x) => x.Item1 == tID);
}
}