Delaying and waking up a task? (Task.Delay?)

I have a situation where I am executing multiple threads at once. In some cases, these threads will be put into a while () loop for an unknown amount of time, and if a certain number of threads get into this loop, then eventually the scheduler stops allowing other threads to execute.

I was wondering if there is a way to slow down the thread execution (remove it from the scheduled list) and then allow other threads. Is it possible then to enlighten this stream with a stream ID or something like that?

I read about Task.Delay and see that it pauses execution from a time interval and that it is possible to release something for an infinite time, but is it possible that this time is infinite until some event happens, and then evade it by name or identifier?

Edit: I thought this question was harder to post code, but more or less I have a situation where requests come in and are placed in a loop, like this:

while(true){
  //check for something that could make me want to delete this thread/request
  //do some things 
 }

      

I noticed that when I sent a large number of requests, which I never stopped, it was still in its loop (which I understand), but it seems that the maximum number of threads that could do this is 16/32 (depends from my computer where I run it) and this stops other requests from being executed.

I wanted to know if something like this could be done inside the while () loop:

while(true){
     //put this thread to sleep
     //do some things that 
     //call some function to wake up the specific thread I need to do work on, before I put it back to sleep
 }

      

The difference is that instead of running 16/32 threads, I can have 1 "corona thread" that goes into this while () loop that can "do some things" and then wake up the thread that needs to be touched "things". Is there a way to sleep and wake up a particular thread so that other threads can be scheduled to start?

+3


source to share


1 answer


From the question, I am assuming you are running a busy wait loop. This is very bad, as you learned.

Make the loop wait for the event:

while (true) {
 WaitForEvent();
 DoWork();
}

      



This requires collaboration with the thread (or component) through which the event occurs. You can use ManualResetEvent

or TaskCompletionSource

to make this coordination happen.

I cannot be more specific, because the question is not particularly specific regarding the scenario. Hopefully this will nudge you in the right direction.

+1


source







All Articles