简体   繁体   中英

when the event loop starts in Dart and how the event queue works

The first question is when the event loop starts? I read in a site that it's start after the main method but why when we try something like this

main()async {
Future(()=>print('future1'));
await Future(()=>print('future2'));
print('end of main');
}

//the output is :
//future1
//future2
//end of main

in this example the event loop start when we use the await keyword and after the event loop reaches the future2 it's paused? or i am wrong:(

The second question is how the events is added to event queue if it's FIFO why in this example the future 2 is completed before future 1

main(){
Future.delayed(Duration(seconds:5) , ()=>print('future1'));
Future.delayed(Duration(seconds:2) , ()=>print('future2')); 
}

The event loop run when there is nothing else running ( eg main method is done, you are waiting for some future to complete ).

Your example makes sense because the first line puts an event on event queue so now the first item in the queue is "print('future1')". In the next line, you are putting another event on the queue which calls "print('future2')" and now you await for this event to be done.

Since your main method is not waiting for something then the event loop is going to be executed. Since the first event on the queue was "print('future1')" then this is going to be executed first. But since the main method is still waiting for the future "print('future2')" to be complete then the event loop takes another event to be executed which are going to be "print('future2')".

Since this event was the one the main method was waiting for (and there is no more event on the event queue) then main() are going to run the last call "print('end of main')".

In your next example, you think that Future and Future.delayed are the same which it is not. With Future.delayed there are not going any event in the event queue before. Instead, there are running a thread outside the VM which knows when the next timer should trigger which ends up putting an event on the queue. So the event is only being put on the event queue when the timer has been expired (and therefore, the future2 are going to be executed first).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM