0

I have n number of threads which run a method routine. With each thread running the search method, and searching for items in a given range, the items are retrieved from a web server. But I believe that they keep on running, even when the range is exhausted. I am using a for loop to determine when the thread should stop searching, but that is not working out. This is what I have:

In method Start() I compute a certain range, and that range is given to a thread, which is to search in this given range.

public void Start()
    {
        this.totalRangePerThread = ((this.endRange - this.startRange) / this.subWorkerThreads.Length);
        for (int i = 0; i < this.subWorkerThreads.Length; ++i)
        {
            var copy = startRange;
            this.subWorkerThreads[i] = new Thread(() => searchItem(copy, this.totalRangePerThread));
            this.startRange = this.startRange + this.totalRangePerThread;
        }

        for (int threadIndex = 0; threadIndex < this.subWorkerThreads.Length; ++threadIndex)
            this.subWorkerThreads[threadIndex].Start();
    }

This is my SearchItem() method:

public void searchItem(int start, int pagesToSearchPerThread)
    {
        for (int count = 0; count < pagesToSearchPerThread; ++count)
        {
            start++;
            for (int activeListCount = 0; activeListCount < this.activeListItems.Count; ++activeListCount)
            {

                //further method calls here to webservers..
            }

        }  
    }

I know about using some shared sentinel to determine when to stop a thread, but I fail to comprehend how to apply it here? How should I be handling this scenario, such that a thread aborts gracefully, when its task is completed...

faizanjehangir
  • 2,771
  • 6
  • 45
  • 83
  • 1
    Please cleanup your sample (i.e. remove unrelated commented out code). Also check where `this.activeListItems.Count` comes from and why there is no locking around its usage. – Alexei Levenkov Apr 02 '13 at 06:04
  • I had a discussion [here](http://stackoverflow.com/questions/15577566/use-multiple-threads-to-achieve-efficient-search-from-a-web-server?rq=1), in which I came to know that the variables are scoped within a particular function. Hence, the `lambda` usage..2) `this.activeListItems.Count` is a constant number, it does not change during the execution of threads.. – faizanjehangir Apr 02 '13 at 06:09

0 Answers0