The point at which I understood the JavaScript event loop was when I heard it described as
"When there is nothing to do, check the queue. But only check the queue when there's nothing left to do."
in the video https://www.youtube.com/watch?v=vMfg0xGjcOI.
For example, if the totality of my JS program is
var x = 5.0;
setTimeout(0,function(){console.log("Hey there!");});
for ( var i = 0; i < 10000; ++i ) x = Math.sqrt(x);
console.log("x = " + x);
then the callback function(){console.log("Hey there!");}
is put in the queue and thus will be executed after console.log("x = " + x);
because that's the point at which there's nothing left to do.
In C#, as I understand -- which I don't really understand -- things are different because the equivalent of the "callback" doesn't wait for there to be nothing to do, but instead interrupts the other process(es). That is my interpretation of
Some time after the write request started, the device finishes writing. It notifies the CPU via an interrupt.
The device driver’s Interrupt Service Routine (ISR) responds to the interrupt. An interrupt is a CPU-level event, temporarily seizing control of the CPU away from whatever thread was running. You could think of an ISR as “borrowing” the currently-running thread, but I prefer to think of ISRs as executing at such a low level that the concept of “thread” doesn’t exist - so they come in “beneath” all threads, so to speak.
Anyway, the ISR is properly written, so all it does is tell the device “thank you for the interrupt” and queue a Deferred Procedure Call (DPC).
When the CPU is done being bothered by interrupts, it will get around to its DPCs. DPCs also execute at a level so low that to speak of “threads” is not quite right; like ISRs, DPCs execute directly on the CPU, “beneath” the threading system.
from http://blog.stephencleary.com/2013/11/there-is-no-thread.html. So if I wrote the equivalent of
var x = 5.0;
setTimeout(0,function(){console.log("Hey there!");});
for ( var i = 0; i < 10000; ++i ) x = Math.sqrt(x);
console.log("x = " + x);
in C#, which would be something like
var x = 5.0;
await SomeAsynchronousRoutine();
for ( var i = 0; i < 10000; ++i ) x = Math.Sqrt(x);
Console.WriteLine("x = {0}",x);
the loop for ( var i = 0; i < 10000; ++i )
may in fact be interrupted to deliver the result of SomeAsynchronousRoutine()
.
Or am I totally wrong and should be ashamed for asking a question without doing enough research first?
If you have to describe the C# "event loop" in terms like
"When there is nothing to do, check the queue. But only check the queue when there's nothing left to do."
then how would you describe it?