A
Adam Clauss
OK, my main thread will create some number of other threads (number determined at runtime). Each of these threads creates a form
via a call:
private void ProcessThread()
{
Application.Run(new MyForm());
}
The problem is, I only want up to 10 of these threads to be actively running at the same time. Initially, I had this implemented
via a ThreadPool, but I needed to control the state of the thread apartment, so I am spawning them all individually. So, I am
trying to come up with another way to control their number.
One result I came up with, was in the form's constructor:
bool run = false;
while (!run)
{
lock (this)
{
run = count < MAX_COUNT;
if (run)
count++;
}
if (!run)
System.Threading.Thread.Sleep(100);
}
where count is a private static int of the form class and MAX_COUNT is a private const int. I added a handler for OnClosing, and
have:
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
lock (this)
{
count--;
}
}
However, it seems a lot of the time some of the threads just kind of get stuckand never run, I'm assuming as a result of something
I'm doing here. Any ideas as to what might be wrong?
Or any better ideas on how to handle it?
via a call:
private void ProcessThread()
{
Application.Run(new MyForm());
}
The problem is, I only want up to 10 of these threads to be actively running at the same time. Initially, I had this implemented
via a ThreadPool, but I needed to control the state of the thread apartment, so I am spawning them all individually. So, I am
trying to come up with another way to control their number.
One result I came up with, was in the form's constructor:
bool run = false;
while (!run)
{
lock (this)
{
run = count < MAX_COUNT;
if (run)
count++;
}
if (!run)
System.Threading.Thread.Sleep(100);
}
where count is a private static int of the form class and MAX_COUNT is a private const int. I added a handler for OnClosing, and
have:
private void OnClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
lock (this)
{
count--;
}
}
However, it seems a lot of the time some of the threads just kind of get stuckand never run, I'm assuming as a result of something
I'm doing here. Any ideas as to what might be wrong?
Or any better ideas on how to handle it?