The following describes how to use GCD.

Source: Internet
Author: User

The following describes how to use GCD:
1
Dispatch_async (dispatch_queue_t queue, dispatch_block_t block );
Async indicates asynchronous running, block indicates what you want to do, and queue indicates who you want to handle the task. (In addition to async, there are also sync and delay. This article takes async as an example ).
Why Program Multithreading is used because the program often needs to read data and then update the UI. for a good user experience, Data Reading operations tend to run in the background, so as to avoid blocking the main thread. there are three queue types in GCD for processing.
1. Main queue:
As the name suggests, running in the main thread is obtained by dispatch_get_main_queue. Main queue is required for UI-related operations.
2. Serial quque (private dispatch Queue)
You can add multiple tasks each time you run a task. The execution sequence is FIFO, which is usually generated by a programmer. For example:
1
2
3
4
Nsdate * da = [nsdate date];
Nsstring * dastr = [da description];
Const char * queuename = [dastr utf8string];
Dispatch_queue_t myqueue = dispatch_queue_create (queuename, null );
3. Concurrent Queue (Global dispatch Queue ):
You can run multiple tasks at the same time. The start time of each task is in the order of adding queue, and the end order depends on the respective tasks. Use dispatch_get_global_queue to obtain the task.
So we can get a general idea about the GCD framework:
1
2
3
4
5
6
7
Dispatch_async (getdataqueue, ^ {
// Obtain data. After obtaining a group, refresh the UI.
Dispatch_aysnc (mainqueue, ^ {
// UI updates must be performed in the main thread
};
}
)
It can be seen that GCD is very simple to use. Based on my experience, we will gradually switch from nsoperation to GCD in the future.

Question: If a viewcontroller runs a thread and the viewcontroller is release before the thread ends, what will happen?
After testing, the thread does not end, the viewcontroller keeps it, And the dealloc method is not executed.

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.