Search code examples
iphoneiosmultithreadingqueuedispatch

Run Disptach sync block from async


I am new to Dispatch queue, now am trying to call background operations through this dispatch queue.

Here I have a doubt, please help me in this. In the below example,

whatQueue:- Should it be mainQueue, queueA or shall I create a new Queue?

dispatch_queue_t queueA = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queueA, ^{
     NSMutableArray * items = listofItems;
    for(NSString * str in items)
    {
         //Run a sync block to send str to server
        dispatch_sync(***whatQueue***, ^{

        });
    }
});

Thanks, Phani


Solution

  • You are not explaining too much as to the reasons why you want the inner block to be executed in a sync way. I assume that you want:

    1. to serialize the sending of the strings to the server;

    2. wait for all the strings to be sent before continuing.

    In this case, you can:

    1. execute the network task on the same queueA (no need for a new dispatch);

    2. ensure that your underlying networking layer (NSURLConnection/AFNetworking/ASIHTTP/...) is doing a sync network operation (otherwise, the network request will return immediately and complete in the background in its own thread).