Issue with dispatch_async and asynchronous request

So, the first question: how dispatch_asyncdoes it determine which thread to use? just picks it randomly? I need to do some parsing and basic data, so I don’t want to block the UI thread and use it dispatch_async, but after that I send NSURLRequestto get some more data and the callback is never called (maybe because the thread is already dead).

So what is a good way to do this? And I can not use

sendAsynchronousRequest:queue:completionHandler: 

because the OS for deployment is 4. Now I just send the request inside

dispatch_async(dispatch_get_main_queue(), ^{
});

which is inside a block dispatch_async(myQueue)that does all the parsing and saving of kernel data. But this doesn’t seem right to me, I mean that there should be a way to use dispatch_async and say that it does not kill the tread, right? Since the use of synchronization requests is not an option.

+5
source share
3 answers

So the first question is how dispatch_async determines which thread to use?

GCD. . , dispatch_async . GCD , , - GCD .

, , , :

dispatch_async(myQueue, ^{
    // Do some stuff off the main queue

    dispatch_async(dispatch_get_main_queue(), ^{ 
        // Do something with the UI
    });
});

. , , , myQueue, . , . , , : .

, , NSURLRequest async , . , , ( myQueue), , . , .

GCD , async vs sync , , , , . .

+12

sendAsynchronousRequest:... , , .

, , - +[NSURLRequest sendSynchronousRequest:returningResponse:error:] , +[NSData dataWithContentsOfURL:].

, , , . , :

dispatch_async(yourQueue, ^{
    // Do some stuff

    NSData * fetchedData = [NSData dataWithContentsOfURL: someURL];

    // Do some more stuff with the data

    dispatch_async(dispatch_get_main_queue(), ^{
       // Do some stuff on the main queue
    }
});
+3

, , , NSURLConnection . . ;) , . _isFinishedLoading true .

, , NSURLConnection . , , , .

NSURLConnection* connection = [NSURLConnection connectionWithRequest:urlRequest delegate:self];
[connection start];
NSRunLoop *runloop = [NSRunLoop currentRunLoop];
_isFinishedLoading = NO;
while (!_isFinishedLoading)
{
    [runloop runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}
0

All Articles