FutureBasic Logo

<<    Index    >> FutureBasic

dispatchglobal, dispatchmain   statement



Syntax
dispatchglobal [[after] ,priority]
// code
dispatchend

dispatchmain [after]
// code
dispatchend

Description
dispatchglobal and dispatchmain submit a block (i.e. the code between dispatchglobal or dispatchmain and its closing dispatchend statement) for asynchronous execution on a dispatch queue and return immediately. Blocks can be nested and each block must be terminated with the dispatchend statement.

Parameters
Parameter
Description
after Optional. Enqueues the block for execution at the specified time (seconds from now).
priority Optional. The queue priority:
_dispatchPriorityDefault (default)
_dispatchPriorityBackground
_dispatchPriorityHigh
_dispatchPriorityLow
 

Examples
(1)
dispatchglobal // run global queue immediately and at default priority
// do something on global queue
dispatchend

(2)
dispatchglobal 5 // run queue in 5 seconds from now at default priority
// do something
dispatchend

(3)
dispatchglobal , _dispatchPriorityLow // run queue immediately at low priority
// do something
dispatchend

(4)
dispatchglobal 2, _dispatchPriorityHigh // run queue in 2 seconds from now at high priority
// do something
dispatchend

(5)
dispatchglobal // run global queue immediately and at default priority
// do something on global queue
dispatchmain
// do something on main thread (such as change UI elements)
dispatchend
dispatchend

Variables
Variables declared outside a block are available inside the block but are immutable unless they are declared with the block statement. Variables declared inside a block are mutable but not available outside the block.

Examples
(1)
dispatchglobal
long
for i = 0 to 99
 // ...
next
dispatchend
// variable 'i' not available here

(2)
block long i // this variable can be changed inside or outside the block
long a = 5 // this variable cannot be changed inside the block
dispatchglobal
for i = 0 to 99
NSLog(@"%ld",i * a)
next
dispatchend

Notes on GCD's behavior (whether using these statements or not)

  1. These statements do not change GCD's scheduling and dispatch behavior. Even using the optional 'after' and 'priority' parameters, GCD decides when and in which order a queued thread executes.
  2. Submitting a block of code to a queue does not mean immediate execution; GCD decides when it will execute the block.
  3. Code sequentially following a dispatchend executes virtually immediately and could easily complete before the dispatched task completes (especially true for a dispatched task that might take more time). In other words, code after the dispatchend cannot/should not assume the dispatched task has completed.

See also
block
 
Apple documentation
Dispatch