Hi
I have following problem: I'm creating two threads who are performing some
tasks. When one thread finished I would like to restart her again (e.g. new
job). Following example demonstrates that. Problem is that when program is
started many threads are created (see output section), when only two should
be running at any time. Can you please help me to identify me where the
problem is?
Best regards
Ivan
Source
================
private void btnStartThreads_Click(object sender, System.EventArgs e)
{
JobAgent ag1 = new JobAgent ();
JobAgent ag2 = new JobAgent ();
while (true)
{
if (ag1.IsRunning == false)
{
Thread t1 = new Thread (new ThreadStart (ag1.Run));
t1.Start ();
}
if (ag2.IsRunning == false)
{
Thread t2 = new Thread (new ThreadStart (ag2.Run));
t2.Start ();
}
}
}
}
public class JobAgent
{
protected ThreadStatus status = new ThreadStatus ();
public void Run ()
{
IsRunning = true;
Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " started");
Thread.Sleep (5000);
Debug.WriteLine ("Thread num. " + Convert.ToString
(Thread.CurrentThread.GetHashCode ()) + " finished");
IsRunning = false;
}
public bool IsRunning
{
get
{
lock (status)
{
return status.isRunning;
}
}
set
{
lock (status)
{
status.isRunning = value;
}
}
}
}
public class ThreadStatus
{
public bool isRunning = false;
}
}
Output
================
Thread num. 10 started
Thread num. 13 started
Thread num. 14 started
Thread num. 15 started
Thread num. 16 started
Thread num. 17 started
Thread num. 18 started
Thread num. 58 started
Thread num. 11 started
Thread num. 12 started
Thread num. 19 started
Thread num. 20 started
Thread num. 21 started
Thread num. 22 started
Thread num. 23 started
Thread num. 24 started
Thread num. 57 started
Thread num. 25 started
Thread num. 26 started
Thread num. 27 started
Thread num. 28 started
Thread num. 10 finished
The thread '<No Name>' (0x1544) has exited with code 0 (0x0).
Thread num. 13 finished
The thread '<No Name>' (0x12dc) has exited with code 0 (0x0).
Thread num. 14 finished
The thread '<No Name>' (0xabc) has exited with code 0 (0x0).
Thread num. 15 finished
The thread '<No Name>' (0x930) has exited with code 0 (0x0).
Thread num. 17 finished
Thread num. 18 finished
The thread '<No Name>' (0xd7c) has exited with code 0 (0x0).
Thread num. 16 finished
The thread '<No Name>' (0xda8) has exited with code 0 (0x0).
Thread num. 29 started
The thread '<No Name>' (0x1590) has exited with code 0 (0x0).