PerformSelector in iOS multithreading: different from dispatch_time
Timer-related latency calls in iOS, which are common in NSObjectOptional mselector: withObject: afterDelay:When this method is called, it will set the timer in the current runloop. There is also a latency, which can be directly usedNSTimerTo configure the task.
Both methods share a common premise, that is, the current thread requires a running runloop and a timer in this runloop.
We know that only the main thread will automatically run a runloop when it is created, and there is a timer, which is not available for common subthreads. This poses a problem. Sometimes we are not sure whether our module will be called asynchronously, however, when writing such delayed calls, we generally do not check the runtime environment, so that when the subthread is called, the code for delayed calling in our code will always wait for timer scheduling, but in fact there is no such timer in the Child thread, so our code will never be tuned.
The following code shows the differences between performSelector and dispatch_time.
/* TestDispatch_after delay added to the queue */-(void) testDispatch_after {interval time = dispatch_time (DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC); dispatch_after (time, interval (), ^ {NSLog (@ "added to queue after 3 seconds") ;}) ;}- (void) testDelay {NSLog (@ "testDelay executed after 3 seconds ");} /* dispatch_barrier_async fence function */-(void) testDispatch_Barrier {// dispatch_queue_t gcd = dispatch_queue_create ("this is a sequence queue", NULL ); dispatch_queue_t gcd = dispatch_queue_create ("this is a concurrent queue", queue); dispatch_async (gcd, ^ {NSLog (@ "b0"); // This selector does not execute [self executor mselector: @ selector (testDelay) withObject: nil afterDelay: 3]; // The Code will be executed // [self testDispatch_after] ;}); dispatch_release (gcd );}In a multi-threaded environment,
In this way, the delayed call of the performSelector lacks security.. We can use another solution to solve this problem, that is, using dispatch_after in GCD to implement a single delay call.