运行线程时Windows窗体挂起

时间:2010-03-11 16:30:36

标签: c# multithreading thread-safety semaphore

JI在Visual Studio 2008中编写了一个.NET C#Windows窗体应用程序,当按下“开始”按钮时,该应用程序使用信号量作为线程运行多个作业。

遇到问题,表格在运行40分钟或更长时间后进入逗号。日志文件表明当前作业已完成,它从列表中选择一个新作业,然后挂起。

我注意到Windows窗体在发生这种情况时变得没有响应。表单在自己的主题中运行。

这是我正在使用的代码示例:

protected void ProcessJobsWithStatus (Status status)
        {
int maxJobThreads = Convert.ToInt32(ConfigurationManager.AppSettings["MaxJobThreads"]);
            Semaphore semaphore = new Semaphore(maxJobThreads, maxJobThreads);  // Available=3; Capacity=3


            int threadTimeOut = Convert.ToInt32(ConfigurationManager.AppSettings["ThreadSemaphoreWait"]);//in Seconds
            //gets a list of jobs from a DB Query.
List<Job> jobList = jobQueue.GetJobsWithStatus(status);
            //we need to create a list of threads to check if they all have stopped.
            List<Thread> threadList = new List<Thread>();
            if (jobList.Count > 0)
            {
                foreach (Job job in jobList)
                {
                    logger.DebugFormat("Waiting green light for JobId: [{0}]", job.JobId.ToString());
                    if (!semaphore.WaitOne(threadTimeOut * 1000))
                    {
                        logger.ErrorFormat("Semaphore Timeout. A thread did NOT complete in time[{0} seconds]. JobId: [{1}] will start", threadTimeOut, job.JobId.ToString());

                    }

                    logger.DebugFormat("Acquired green light for JobId: [{0}]", job.JobId.ToString());
                    // Only N threads can get here at once    
                    job.semaphore = semaphore;
                    ThreadStart threadStart = new ThreadStart(job.Process);

                    Thread thread = new Thread(threadStart);
                    thread.Name = job.JobId.ToString();
                    threadList.Add(thread);
                    thread.Start();


                }

                logger.Info("Waiting for all threads to complete");

                //check that all threads have completed.
                foreach (Thread thread in threadList)
                {
                    logger.DebugFormat("About to join thread(jobId): {0}", thread.Name);
                    if (!thread.Join(threadTimeOut * 1000))
                    {
                        logger.ErrorFormat("Thread did NOT complete in time[{0} seconds]. JobId: [{1}]", threadTimeOut, thread.Name);
                    }
                    else {
                        logger.DebugFormat("Thread did complete in time. JobId: [{0}]", thread.Name);
                    }
                }                   

            }

            logger.InfoFormat("Finished Processing Jobs in Queue with status [{0}]...", status);

}

//表单方法

private void button1_Click(object sender, EventArgs e)
        {
            buttonStop.Enabled = true;
            buttonStart.Enabled = false;

            ThreadStart threadStart = new ThreadStart(DoWork);
            workerThread = new Thread(threadStart);

            serviceStarted = true;
            workerThread.Start();



        }

private void DoWork()
        {
            EmailAlert emailAlert = new EmailAlert ();
            // start an endless loop; loop will abort only when "serviceStarted" flag = false
            while (serviceStarted)
            {  
                emailAlert.ProcessJobsWithStatus(0);

                // yield
                if (serviceStarted)
                {
                    Thread.Sleep(new TimeSpan(0, 0, 1));
                }
            }

            // time to end the thread
            Thread.CurrentThread.Abort();
        }

// job.process()

 public void Process()
        {
             try
            {

                //sets the status, DateTimeStarted, and the processId
                this.UpdateStatus(Status.InProgress);

                //do something

                logger.Debug("Updating Status to [Completed]");

                //hits, status,DateFinished
                this.UpdateStatus(Status.Completed);

            }
            catch (Exception e)
            {
                logger.Error("Exception: " + e.Message);
                this.UpdateStatus(Status.Error);

            }
            finally {
                logger.Debug("Relasing semaphore");
                semaphore.Release();
            }

我已经尝试将我可以记录到文件中以检测问题发生的位置,但到目前为止,我还无法确定这种情况发生的位置。失去对Windows窗体的控制使我认为这与处理作业无关。有什么想法吗?

解决方案:使用RedGate ANTS进行分析产生了这个问题。直接运行时不会发生这种情况。

1 个答案:

答案 0 :(得分:3)

我看到的第一件事就是你的Thread.CurrentThread.Abort()电话。这是不必要的。让函数退出,线程将正常关闭。

我注意到的第二件事是,即使获取信号量发生超时,也会创建一个线程。由于线程过多,您的表单可能会挂起。

logger.DebugFormat("Waiting green light for JobId: [{0}]", job.JobId.ToString());
if (!semaphore.WaitOne(threadTimeOut * 1000))
{
   logger.ErrorFormat("Semaphore Timeout. A thread did NOT complete in time[{0} seconds]. JobId: [{1}] will start", threadTimeOut, job.JobId.ToString());
   // Should have exit here.
}
logger.DebugFormat("Acquired green light for JobId: [{0}]", job.JobId.ToString());

第三件事是你的工作线程正在调用一个函数,该函数只为job循环中的每个作业创建线程。如果一个作业没有完成(假设这导致一个作业被从队列中删除,因为我没有在任何地方看到那个代码。)在DoWork从睡眠状态唤醒它之前,它将迭代同一个作业并尝试创建另一个作业它的线程。

相关问题