-2

Having long running Task, something like this

Task.Factory.StartNew(() =>
{
    var step = 0;
    while (true)
    {
        Task.Delay(100).Wait();                 
        Console.WriteLine(step);
        step++;
        if (step > MaxStep)
        {
            return;
        }
    }
}, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default);

In the same application there are lots of Tasks with API calls executing and when, sometimes that API calls are slowing down, this main long running task having disturbance, taking more than 150 milliseconds to the next step. How can I make this task flawless? Any ideas?

Tried to use Thread on place of Task, same result. Wanted to change API calls to async but too much refactoring in old code, scared to touch it. Artifically wrapped methods with API calls to async methods but same result.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104

1 Answers1

0

Have you tried running a

backgroundWorker

instead of Tasks (They are not the same though). Another quick way to achieve this is using

Timers

or

DispatcherTimer

). I have used timers to run 24-hours (weeks) window that shows Ads continuously with no error.

  • If you could provide more details about what you are doing in your app, I will try to help. – Prefetcher Shatnawi Feb 19 '23 at 20:47
  • BackgroundWorker and Timers are all using threads, if something can't be done on Thread, I don't think it can be done in them. Checked BW/Timers and same result. Thanks though. Question is more about, if I can tell Thread that you are very important and can allocate CPU resource for it, which can't be touched from other threads. – Rezo Khurtsilava Feb 20 '23 at 08:04
  • If your code needs excessive use of cpu resources then you must be implementing your design inefficiently. Can you share the code you are trying to run asynchronously or provide more details about your project. – Prefetcher Shatnawi Feb 20 '23 at 08:09
  • Fyi, timers doesn’t implement threads. It’s more similar to hardware interrupts that gets triggered within OS software interrupts. – Prefetcher Shatnawi Feb 20 '23 at 08:12