Assuming that the starting point will not have process / thread / task control and be an unresponsive spinning cycle, checking if the time has passed, for example:
public void SleepBadly(int millisecondsTimeout) { var stopTime = DateTime.UtcNow.AddMilliseconds(millisecondsTimeout); while (DateTime.UtcNow < stopTime) {} return; }
SleepAsyncA sleeps the stream, but does not rotate, so it does not use any processor, so it will be responsive as the processor is available, but it still uses the stream while it sleeps.
SleepAsyncB rejects the thread while it is waiting, so it does not use the CPU and this thread can be used for something else; therefore responsive and scalable .
For example, to scale if you had 100,000 calls in SleepAsyncA; either you would run out of thread and they would start the queues, or you would have 100,000 active threads, none of which are very good for scalability.
SleepAsyncB, on the other hand, will use 0 threads, while 100,000 calls are waiting, and does nothing infinitely more scalable than doing something.
However, while SleepAsyncB is a good example of using Task constructs such as TaskCompletionSource, what you probably would like to do in this example is:
public Task SleepAsyncC(int millisecondsTimeout) { return Task.Delay(millisecondsTimeout); }
Ben adams
source share