0

This is the code I am using to call 3 threads.

for (int i = 0; i < 3; i++)
{
    new Thread(() => { processEventLogTesting(); }) {IsBackground = true }.Start();
}

I was thinking about adjusting it to this

public static int ThreadCounter = 0;

if (ThreadCounter < 3)
{
    ThreadCounter ++;
    for (int i = 0; i < 3; i++)
    {
        new Thread(() => 
        {
            processEventLogTesting(/*somewhere in here code says */ThreadCounter--;);}) {IsBackground = true }.Start();
        }
    }
}

However, I think this is probably not the best way to do this. Also, I want to put in a new timer that says if thread x goes over 20 minutes, kill thread x. Any help is appreciated.

Jalal Said
  • 15,906
  • 7
  • 45
  • 68
  • 1
    What's the thread doing? – jglouie Jul 20 '11 at 21:05
  • 4
    Careful with that axe, Eugene. What you are trying to do is *super dangerous*. Write your code so that it shuts itself down cleanly; do not abort the thread. See http://blogs.msdn.com/b/ericlippert/archive/2010/02/22/should-i-specify-a-timeout.aspx for more details. – Eric Lippert Jul 20 '11 at 21:38

1 Answers1

-1

Since I don't know what thread does, I would try something like this

        private Object lockObject = new Object();
        private int threadCounter = 0;
        public int ThreadCounter
        {
            get
            {
                lock(lockObject)
                { 
                    return threadCounter;
                } 
            }            
            set
            {
                lock(lockObject)
                { 
                    threadCounter = value;
                } 
            }
        }

        //this should be a method
        if (ThreadCounter < 3)
        {
            ThreadCounter ++;
            new Thread(() => 
            {
                Timer t = new Timer(() => EndThread(), null, 0, 20 * 60 * 1000);
                while(threadIsRunning)
                {                     
                     processEventLogTesting(/*somewhere in here code says ThreadCounter--*/;);
                }
            }) {IsBackground = true }.Start();

                }
            }
        }

        private void EndThread()
        {
            threadIsRunning = false;
        }
Marin
  • 66
  • 1
  • 2
  • 7