Skip to content

Thread Headache

Thomas Sieverding

Asked Aug 19, 2007, 3:36 PM EDT2 answers
Share
LinkedInX
Ok so, the program I created needs to launch a variable amount of threads between 300-600 and be able to close individual threads/all threads at any time. Boolean checking is not an option - not all threads will close by the time new threads start and the program will not function. I'm looking for a way to give each thread an id and store it in an array parallel to variables_to_monitor so that the indexes match up and can be used to look up the id based on the index and terminate. Any ideas/help would be wonderful!!

private bool[] = new bool[0x301];
private Thread ThrScanner;
private int[] variables_to_monitor;
private int argument_to_pass;
private void timer1_Tick(object sender, EventArgs e)
{
for (int i = 0; i <= 0x300; i++)
{
if (variables_to_monitor[ i ] != 0 & !bool[ i ])
{
bool[ i ] = true;
arguement_to_pass = i;
ThrScanner = new Thread(Monitor);
ThrScanner.IsBackground = true;
ThrScanner.Start();
}
}
}

private void Monitor();
{
while (true)
{
int compare_variables = variables_to_monitor[arguement_to_pass];
while(compare_variables == variables_to_monitor)
{ System.Threading.Thread.Sleep(10); }
// variables changed, event triggered
}
}

private void button_Click(object sender, System.EventArgs e)
{
ThrScanner.Abort();
bool[] = new bool[0x301];
ThrScanner.Join();
}

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • 0
    I think that a more c#ish way of doing it is to maintain an ArrayList of your threads.

    ArrayList myThreads = new ArrayList();
    ...

    myThreads.Add(eachNewThread);

    You can loop through the threads at anytime with:

    foreach (Thread thisThread in myThreads)....

    If you need to stop any given thread, then you presumably already have reference to that thread.

    When I am managing a large number of complex objects like threads, I design an interface (if they are differing but similar) or an object inheriting from whatever (Thread in this case).  Then I can code in any attributes or methods to support the things I want to do with all of them. 
    0
  • 0
    Thx! It hadn't occured to me to store the threads in an array.. didn't know that would work well. I suppose then assuming your technique works, I could also store each thread in a hashtable which would let me better identify the thread.
    0