Scalability and responsiveness in .NET Async

I read through Exam Ref 70-483: Programming in C # and the following code example is given:

LISTING 1-19

public Task SleepAsyncA(int millisecondsTimeout) { return Task.Run(() => thread.Sleep(millisecondsTimeout); } public Task SleepAsyncB(int millisecondsTimeout) { TaskCompletionSource<bool> tcs = null; var t = new Timer(delegate { tcs.TrySetResult(true); }, -1, -1); tcs = new TaskCompletionSource<bool>(t); t.Change(millisecondsTimeout, -1); return tcs.Task; } 

The paragraph under the heading reads as follows:

The SleepAsyncA method uses a thread from a thread pool while sleeping. the second method, however, which has a completely different implementation, does not take a thread, waiting for a timer to start. The second way gives you scalability.

Why responsive but scalable?

+7
multithreading c # scalability async-await
source share
2 answers

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); } 
+9
source share

A is responsive because it has the appearance of asynchrony, without blocking the thread, which is important to the user. The user interface remains fluid, but it does not scale, because under the hood it binds a limited resource (blocking the flow).

B is still responsive , but also scalable because it is really asynchronous, not just the look. It does not bind limited resources, even if the user interface remains fluid.

+6
source share

All Articles