for循环执行后多线程不终止

时间:2013-04-02 05:45:21

标签: c# multithreading

我有n个运行方法例程的线程。每个线程运行搜索方法,并搜索给定范围内的项目,从Web服务器检索项目。但是我相信它们会继续运行,即使范围已经耗尽。我正在使用for循环来确定线程何时应该停止搜索,但这没有用。这就是我所拥有的:

在方法Start()中,我计算了一定的范围,并且该范围被赋予一个线程,该线程将在此给定范围内进行搜索。

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();
    }

这是我的SearchItem()方法:

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..
            }

        }  
    }

我知道使用一些共享的哨兵来确定何时停止一个帖子,但是我不理解如何在这里应用它?我应该如何处理这种情况,以便线程在其任务完成时正常中止......

0 个答案:

没有答案