Is it possible to call the performSelectorOnMainThread function: after calling the beginBackgroundTaskWithExpirationHandler function and the application is in the background?

I run the background job as follows:

UIApplication* application = [UIApplication sharedApplication]; _backgroundTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^ { [application endBackgroundTask:_backgroundTask]; _backgroundTask = UIBackgroundTaskInvalid; }]; 

The application is sent to the wallpaper , and everything is in order.

After a while, a certain condition is satisfied, and some object finishes executing this code:

 [self performSelectorOnMainThread:@selector(doSomething) withObject:nil waitUntilDone:YES]; 

At this point, the application will work!

Note that the object runs in the main thread in this particular case.

I replaced the above code with the following:

  dispatch_async(dispatch_get_main_queue(), ^{ [self doSomething]; }); 

And everything seems OK, the crash is gone.

What I can imagine is that waitUntilDone: YES may be the difference here, but that is just my gut feeling.

My question is:

Is it allowed to use performSelectorOnMainThread: withObject: waitUntilDone: YES when the application is running in the background?

If so, why did the application crash and why did dispatch_async solve the problem?

Thanks in advance!

+6
source share
1 answer

Using performSelectorOnMainThread: withObject: waitUntilDone: YES can cause deadlocks to jam. The current thread stops and waits. If the main thread does not complete the selector in time, iOS can kill your application to bind the main thread more than the allowed time (usually 10 seconds, and sometimes less).

Calling dispatch_async (dispatch_get_main_queue ... does not block this path). It always puts the event in the queue and waits for its turn, and the current thread continues without stopping.

It is difficult to say what happened without additional information about the nature of the accident.

+1
source

Source: https://habr.com/ru/post/916956/