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

  • SEARCH
  • Home
  • 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 6579985
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T15:58:01+00:00 2026-05-25T15:58:01+00:00

I am looking for the correct way/structure to create a loop in a Thread/Task

  • 0

I am looking for the correct way/structure to create a loop in a Thread/Task…

The reason for this is, i need to check the DB every 15sec for report requests.

This is what i tried so far, but i get OutOfMemoryException:

    private void ViewBase_Loaded(object sender, RoutedEventArgs e)
{
    //On my main view loaded start thread to check report requests.
    Task.Factory.StartNew(() => CreateAndStartReportRequestTask());
}

private void CreateAndStartReportRequestTask()
{
    bool noRequest = false;

    do
    {
         //Starting thread to Check Report Requests And Generate Reports
         //Also need the ability to Wait/Sleep when there are noRequest.
         reportRequestTask = Task.Factory.StartNew(() => noRequest = CheckReportRequestsAndGenerateReports());

         if (noRequest)
         {
             //Sleep 15sec
             reportRequestTask.Wait(15000);
             reportRequestTask = null;
         }
         else
         {
             if (reportRequestTask.IsCompleted)
             {
                 reportRequestTask = null;
             }
             else
             {
                 //Don't want the loop to continue until the first request is done
                 //Reason for this is, losts of new threads being create in CheckReportRequestsAndGenerateReports()
                 //Looping until first request is done.
                 do
                 {

                 } while (!reportRequestTask.IsCompleted);

                 reportRequestTask = null;
             }
         }

    } while (true);
}

private bool CheckReportRequestsAndGenerateReports()
{
    var possibleReportRequest = //Some linq query to check for new requests

    if (possibleReportRequest != null)
    {
        //Processing report here - lots of new threads/task in here as well
        return false;
    }
    else
    {
        return true;
    }
}

What am i doing wrong?

Is this correct way or am i total off?

EDIT:

Most important, my UI must still be responsive!

  • 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-25T15:58:02+00:00Added an answer on May 25, 2026 at 3:58 pm

    Sounds like you want something like this. Please correct me if I am misinterpretting your intentions…

    First, in your kick-off, set as a long running task so it doesn’t consume a thread from the thread pool but creates a new one…

    private void ViewBase_Loaded(object sender, RoutedEventArgs e)
    {
        // store this references as a private member, call Cancel() on it if UI wants to stop
        _cancelationTokenSource = new CancellationTokenSource();
        new Task(() => CreateAndStartReportRequestTask(), _cancelationTokenSource.Token, TaskCreationOptions.LongRunning).Start();
    }
    

    Then, in your report watching thread, loop until IsCancelRequested has been set. If there is no work, just wait on the cancel token for 15 seconds (this way if cancelled will wake sooner).

    private bool CheckReportRequestsAndGenerateReports()
    {
        while (!_cancellationTokenSource.Token.IsCancelRequested) 
        {
            var possibleReportRequest = //Some linq query
            var reportRequestTask = Task.Factory.StartNew(() => noRequest = CheckReportRequestsAndGenerateReports(), _cancellationTokenSource.Token);
    
            if (noRequest)
            {
                // it looks like if no request, you want to sleep 15 seconds, right?
                // so we'll wait to see if cancelled in next 15 seconds.
                _cancellationTokenSource.Token.WaitHandle.WaitOne(15000);
    
            }
            else
            {
                // otherwise, you just want to wait till the task is completed, right?
                reportRequestTask.Wait(_cancellationTokenSource.Token);
            }
        }
    }
    

    I’d also be wary of having your task kick off more tasks. I have a feeling you are spinning up so many you’re consuming too many resources. I think the main reason your program was failing was that you had:

         if (noRequest)
         {
             reportRequestTask.Wait(15000);
             reportRequestTask = null;
         }
    

    This will return immediately and not wait 15s, because the thread is already complete at this point. Switching it to the cancel token (or a Thread.Sleep(), but then you can’t abort it as easily) will give you the processing wait you need.

    Hope this helps, let me know if i’m off on my assumptions.

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

Sidebar

Related Questions

I am looking to the fastest and the correct way to check if a
I'm looking for the correct way to structure the query for a view in
Looking around the docs I cannot see a correct way to go about this.
Hi all and thanks for looking, What is the correct way to do this:
Looking for the correct way and control to import and export of out of
I'm looking for (arguably) the correct way to return data from a XmlHttpRequest .
I am looking at singletons and I was curious about the correct way to
I'm looking for the correct way of using wp_get_attachment_image(). The following code: <?php $args
This is a segue to my previous question: Looking for a better way to
I was recently looking for a way to implement a doubly buffered thread-safe cache

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.