Understanding of IOS dispatch_source_t

Source: Internet
Author: User
Tags gcd set time

Dispatch source is a basic type in gcd, which is literally called a dispatch source, and its role is to capture these events when there are some specific lower-level system events, and then to do other logical processing, with multiple types of dispatch sources, Listen for system events of the corresponding type, respectively. Let's see what the types are:

  • Timer DispatchSource: timing dispatch sources.
  • Signal Dispatch Source: Monitors UNIX signal dispatch sources, such as listening for sigstop signals that represent pending commands .
  • descriptor Dispatch Source: A scheduler that listens for file-related operations and socket -related operations.
  • process DispatchSource: The dispatch sources that monitor the status of the process.
  • Mach Port Dispatch source: A dispatch source that listens for Mach-related events.
  • Custom Dispatch Source: Monitors the dispatch source for custom events.

In layman's words, you use the GCD function to specify a system event type that you want to listen to, and then specify a closure or function that captures the event to be logically processed as a callback function, and then specify a dispatch queue that the callback function executes. The callback function is called when the listener is in the specified system event, and the callback function is placed in the specified queue as a task. This means that when a system event is heard, a task is triggered and automatically queued for execution, which differs from the pattern of manually adding a task, once the Diaptach source is associated with the Dispatch queue, if the system event is heard, Dispatch Source automatically adds the task (callback function) to the associated queue. Sometimes the callback function executes a long time, in this period of time dispatch source and listen to multiple system events, in theory will form an event backlog, but fortunately dispatch source has a good mechanism to solve this problem, When there are multiple event backlogs, they are associated and combined to form a new event based on the event type.

Listener Event Type

Dispatch source can listen to a total of six types of events, divided into 11 categories, we look at what:

    • DISPATCH_SOURCE_TYPE_DATA_ADD: is a custom event, you can dispatch_source_get_data get event variable data through a function, and in our custom method we can call the dispatch_source_merge_data function to set the data to dispatch source, which is shown in detail later in this article.
    • DISPATCH_SOURCE_TYPE_DATA_OR: Belongs to a custom event, using the same type as above.
    • DISPATCH_SOURCE_TYPE_MACH_SEND: Mach port sends events.
    • DISPATCH_SOURCE_TYPE_MACH_RECV: Mach Port receives event.
    • DISPATCH_SOURCE_TYPE_PROC: Process-related events.
    • DISPATCH_SOURCE_TYPE_READ: Read file event.
    • DISPATCH_SOURCE_TYPE_WRITE: Write file event.
    • DISPATCH_SOURCE_TYPE_VNODE: File property Change event.
    • DISPATCH_SOURCE_TYPE_SIGNAL: Receives a signal event.
    • DISPATCH_SOURCE_TYPE_TIMER: Timer event.
    • DISPATCH_SOURCE_TYPE_MEMORYPRESSURE: Memory pressure event.
Create Dispatch Source

We can use a dispatch_source_create function to create dispatch Source, which has four parameters:

    • type: The first parameter identifies the type of event that the dispatch source listens on, with a total of 11 types.
    • handle: The second parameter is dependent on the type of event to be monitored, such as if it is a type of Mach port number, if it is an event that listens to an event variable data type, and if it is a listener for events that are of the datatype, mach_port_t the parameter is not required and is set to 0.
    • mask: The third parameter also depends on the type of event to listen to, such as the event that listens for file property changes, which identifies which property of the file, such as DISPATCH_VNODE_RENAME .
    • queue: The fourth parameter sets the queue where the callback function is located.
Nstimeinterval period = 0.1; Set time interval                dispatch_queue_t queue = dispatch_get_global_queue (dispatch_queue_priority_default, 0);d Ispatch_ source_t _timer = dispatch_source_create (dispatch_source_type_timer, 0, 0, queue);//dispatch_source_t _timer type
Setting up event handlers

As mentioned earlier, when the dispatch source hears an event, the specified callback function or closure is invoked, and the callback function or closure is the event handler for dispatch source. We can use the dispatch_source_set_event_handler or dispatch_source_set_event_handler_f function to set the processor to the created dispatch source, which is the processor that sets the form of the closure, which is the processor in the form of a function:

Dispatch_source_set_event_handler (Dispatchsource, {                    print ("Dispatch source event handler ...")})//According to the characteristics of the closure trailing, You can also have the following notation Dispatch_source_set_event_handler (dispatchsource) {    print ("Dispatch source event handler ...")      }

Example:

__block int timeout=300;      Countdown time dispatch_queue_t queue = Dispatch_get_global_queue (Dispatch_queue_priority_default, 0);      dispatch_source_t _timer = dispatch_source_create (dispatch_source_type_timer, 0, 0,queue); Dispatch_source_set_timer (_timer,dispatch_walltime (NULL, 0), 1.0*nsec_per_sec, 0); No second execution Dispatch_source_set_event_handler (_timer, ^{if (timeout<=0) {//Countdown end, close Dispatch_sour              Ce_cancel (_timer);              Dispatch_release (_timer);              Dispatch_async (Dispatch_get_main_queue (), ^{//Settings Interface button display According to your own needs set ....          });              }else{int minutes = TIMEOUT/60;              int seconds = timeout% 60;              NSString *strtime = [NSString stringwithformat:@ "%d minutes%.2d seconds after re-obtaining the verification code", minutes, seconds];              Dispatch_async (Dispatch_get_main_queue (), ^{//Settings Interface button display According to your own needs set ....              });                        timeout--;      }      }); DIspatch_resume (_timer);   

Since it is the event handler, it is necessary to obtain some information about the dispatch source, and GCD provides three functions to obtain information about dispatch source in the processor, such as handle mask . And for different types of dispatch Source, the values and types of the three functions return data, and the following is a look at these three functions:

    • dispatch_source_get_handle: This function is used to get the second parameter set when creating dispatch source handle .
      • If the dispatch Source is a read-write file, the descriptor is returned.
      • If the dispatch source is a signal type, the number of signals of the type is returned int .
      • If the dispatch Source is a process type, the process ID of the type is returned pid_t .
      • If the dispatch Source is a Mach port type, the mach_port_t type of Mach port is returned.
    • dispatch_source_get_data: This function is used to obtain data about the dispatch source monitor event.
      • If the dispatch Source of the file type is read, the number of bytes read to the file content is returned.
      • If it is a dispatch Source that writes a file type, returns whether the file is writable, the positive number is writable, and the negative number indicates that it is not writable.
      • If the dispatch Source is a listener file property change type, it returns the changed file attributes that were heard, expressed as constants, for example, DISPATCH_VNODE_RENAME and so on.
      • If the dispatch Source is a process type, return to the state of the process being heard, expressed as constants, for example DISPATCH_PROC_EXIT .
      • If it is a dispatch Source of the Mach port type, return the state of the Mach port, expressed as a constant, for example DISPATCH_MACH_SEND_DEAD .
      • If the dispatch Source is a custom event type, returns data that is dispatch_source_merge_data set using the function.
    • dispatch_source_get_mask: This function is used to get the third parameter set when creating a dispatch source mask . In the process type, file property change type, mach port type dispatch source, the function returns the dispatch_source_get_data same as the result.
Register Cancellation Handler

Cancellation handler is used when dispatch source is disposed to handle some subsequent things, such as closing the file descriptor or releasing the Mach port. We can use dispatch_source_set_cancel_handler functions or dispatch_source_set_cancel_handler_f functions to register cancellation Handler with dispatch Source: 

Dispatch_source_set_cancel_handler (dispatchsource) {                print ("for aftercare ...")      }

  

The function has two parameters, the first parameter is the target dispatch Source, and the second parameter is a closure or function to be processed.

Change the destination queue for dispatch source

In the above, we said that we could use the dispatch_source_create function to create the dispatch Source and specify the queue that the callback function executes when it is created, so if you want to change the queue later, for example, if you want to change the priority of the queue, then we can use the dispatch_set_target_queue function: Swift

Let dispatchqueuedefaultpriority = Dispatch_get_global_queue (dispatch_queue_priority_default, 0) Let        Dispatchsource = dispatch_source_create (dispatch_source_type_data_add, 0, 0, dispatchqueuedefaultpriority) let   dispatchqueuelowpriority = Dispatch_get_global_queue (dispatch_queue_priority_low, 0)     dispatch_set_target_ Queue (Dispatchsource, dispatchqueuelowpriority)

 

It is important to note that if the Dispatch source has already heard the relevant event when the target queue is changed, and the callback function has been executed in the previous queue, it will continue to be completed in the old queue and will not be transferred to the new queue.

Pause Recovery Dispatch Source

Pause and resume dispatch source is the same as the dispatch queue, dispatch_suspend and functions are applicable dispatch_resume . It is important to note that the newly created dispatch source is in a paused state, so it needs to be started with a function when it is used dispatch_resume .

Repeal Dispatch Source

If we no longer need to use a dispatch source, we can use the dispatch_source_cancel function repeal, which has only one parameter, which is the target dispatch source.

Dispatch Source Practice

Say so much, this section to see Dispatch source exactly how to use.

Using dispatch source to monitor timers

Dispatch one of the types of events that source can listen to is the timer, let's see how it's implemented: Swift

Class Testdispatchsource {      
Func launch () {
Let Dispatchqueue = Dispatch_get_global_queue (dispatch_queue_priority_default, 0)
Let timer = Createtimerdispatchsource (dispatch_time (dispatch_time_now, 0), Interval:nsec_per_sec * 5, leeway:0, queue:d Ispatchqueue) {
Print ("Process timed task, this task executes every 5 seconds ...") } dispatch_resume (timer) sleep (+) }
Func Createtimerdispatchsource (starttime:dispatch_time_t, Interval:uint64, Leeway:uint64, queue:dispatch_queue_t, handler:dispatch_block_t), dispatch_source_t {
Let Timerdispatchsource = dispatch_source_create (dispatch_source_type_timer, 0, 0, queue)
Dispatch_source_set_timer (Timerdispatchsource, StartTime, interval, leeway)
Dispatch_source_set_event_handler (Timerdispatchsource, handler)
Return Timerdispatchsource }}

  

A new function in the code example above dispatch_source_set_timer is to set the correlation property for the dispatch source of the Listener event type DISPATCH_SOURCE_TYPE_TIMER , which has four parameters:

    • source: This parameter is the target dispatch Source and the type is dispatch_source_t .
    • start: This parameter is the start time of the timer, and the type is dispatch_time_t .
    • interval: This parameter is the time interval of the timer, the type is UInt64 , the unit of time interval is nanosecond.
    • leeway: This parameter is the precision of the interval time, the type is UInt64 , and the time unit is nanoseconds.
Monitoring custom events with dispatch source

Dispatch source can listen for one of the types of events that are custom events, let's look at how to use:

Class Testdispatchsource {        func launch () {        var totalprocess = 0 Let        dispatchsource = Dispatch_source_create ( Dispatch_source_type_data_add, 0, 0, dispatch_get_main_queue ())        Dispatch_source_set_event_handler ( Dispatchsource) {Let            process = Dispatch_source_get_data (dispatchsource)            totalprocess + = Int (process)            Print ("Here you can update the UI in the main thread, show the progress bar ... Progress is/(totalprocess)% ")        }        dispatch_resume (Dispatchsource)        generatecustomevent (dispatchsource)    }    func generatecustomevent (dispatchsource:dispatch_source_t) {let        queue = Dispatch_get_global_queue ( Dispatch_queue_priority_default, 0) for            index in 0...100 {                 Dispatch_sync (QUEUE) {              
Print ("Simulate custom events ... Progress is/(index)% ")
Dispatch_source_merge_data (Dispatchsource, 1) Sleep (2)}}}

 

Let's take a look at the generateCustomEvent(dispatchSource: dispatch_source_t) method, which is to simulate a custom event, create a global concurrency queue first, then loop it to perform the task, and invoke the function in the executed task to dispatch_source_merge_data trigger DISPATCH_SOURCE_TYPE_DATA_ADD DISPATCH_SOURCE_TYPE_DATA_OR The dispatch Source of the listener type. The function has two parameters, the first parameter is the target dispatch Source, the type of the second parameter is an unsigned long integer, and is used to append the specified number to the corresponding variable in the target dispatch source.

Let's take a look at how to listen for custom time, first create a type DISPATCH_SOURCE_TYPE_DATA_ADD of dispatch source, then set the callback closure, use the dispatch_source_get_data get appended variable value in the closure, the function has only one parameter, which is the target dispatch Source, It is important to note that the value dispatch_source_get_data of the variable obtained by the function is not an accumulative value, but rather the value set at each call to the dispatch_source_merge_data function, so in the example above, the totalProcess variable is incremented each time it gets to the value.

The above example can be used to simulate the background to download, based on the amount of data downloaded using a dispatch_source_merge_data function to the target dispatch source set the corresponding variable value, and then in the main thread to hear the dispatch source of the custom event, through the dispatch_source_get_data function to get to the variable, Used to update the UI that displays the progress bar.

Original link: http://www.th7.cn/Program/IOS/201605/849625.shtml

Reference: http://blog.csdn.net/kut00/article/details/8845351

 

Understanding of IOS dispatch_source_t

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.