Method: Kernel#Async

Defined in:
lib/kernel/async.rb

#AsyncObject

Run the given block of code in a task, asynchronously, creating a reactor if necessary.

The preferred method to invoke asynchronous behavior at the top level.

  • When invoked within an existing reactor task, it will run the given block

asynchronously. Will return the task once it has been scheduled.

  • When invoked at the top level, will create and run a reactor, and invoke

the block as an asynchronous task. Will block until the reactor finishes running.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kernel/async.rb', line 24

def Async(...)
	if current = ::Async::Task.current?
		return current.async(...)
	elsif scheduler = Fiber.scheduler
		::Async::Task.run(scheduler, ...)
	else
		# This calls Fiber.set_scheduler(self):
		reactor = ::Async::Reactor.new
		
		begin
			return reactor.run(...)
		ensure
			Fiber.set_scheduler(nil)
		end
	end
end