Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 653609
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T22:24:05+00:00 2026-05-13T22:24:05+00:00

JI have written a .NET C# Windows Form app in Visual Studio 2008 that

  • 0

JI have written a .NET C# Windows Form app in Visual Studio 2008 that uses a Semaphore to run multiple jobs as threads when the Start button is pressed.

It’s experiencing an issue where the Form goes into a comma after being run for 40 minutes or more. The log files indicate that the current jobs complete, it picks a new job from the list, and there it hangs.

I have noticed that the Windows Form becomes unresponsive when this happens. The form is running in its own thread.

This is a sample of the code I am using:

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

}

//form methods

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

I have tried to log what I can into a file to detect where the problem is happening, but so far I haven’t been able to identify where this happens. Losing control of the Windows Form makes me think that this has nothing to do with processing the jobs. Any ideas?

Solution: Profiling it with RedGate ANTS was producing the issue. It does not happen when run directly.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T22:24:05+00:00Added an answer on May 13, 2026 at 10:24 pm

    The first thing I see is your Thread.CurrentThread.Abort() call. This is unnecessary. Let the function exit and the thread will shut down gracefully.

    The second thing I noticed is that even if a timeout occurs for acquiring a semaphore a thread will be created anyway. Your form could be hanging as a result of too many threads.

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

    The third thing is your worker thread is calling a function which simply creates threads for every job in the jobs loop. If a job doesn’t complete (assuming this causes a job to be removed from the queue since I don’t see that code anywhere.) before DoWork wakes up from it’s sleep it’s going to iterate over the same Job and try to create another thread for it.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.