search

Home  >  Q&A  >  body text

objective-c - GCDAsyncsocket always fails to execute when placed in a child thread. What's going on?

GCDAsyncsocket uses the asynchronous serial sub-thread to stop executing the for loop halfway through. The code is as follows. The process is to click the send button to return to the main page, and then execute the following code asynchronously to upload the image;

    
    - (void)sendAction{
      dispatch_queue_t queue = dispatch_queue_create("uploadImage", DISPATCH_QUEUE_SERIAL);
         dispatch_async(queue, ^{
       for (int i =0; i < 10; i++) {
              
         NSLog(@"async ------------ %@", [NSThread currentThread]);
        
        //第一张图的资源
        PHAsset *asset = self.sendImageArray[i];
        NSString *fileType;
        NSString *fileName;
      
        if (asset.mediaType == PHAssetMediaTypeImage) {
            fileType = @"jpg";
            NSData *data = [NSData dataWithContentsOfFile:filePath[i]];

            [self upLoadImageData:data type:@"jpg" name:fileName];
        } else if(asset.mediaType == PHAssetMediaTypeVideo) {
            fileType = @"mp4";
              NSData *data = [NSData dataWithContentsOfFile:filePath[i]];
            [self uploadMp4Data:data type:fileType name:fileName];
            
        }       
  }
  });
  }
  
  - (void)upLoadImageData:(NSData*)data  type:(NSString *)fileType name:(NSString *)fileName{
     dataNameMutStr = [NSMutableString stringWithFormat:@"ios_%@_%@.jpg\n", @"图片",fileName];
   NSData *dataName = [dataNameMutStr dataUsingEncoding:NSUTF8StringEncoding];
   [self sendSocket:dataName data:data];
   }
   
   
   - (void)sendSocket:(NSData *)dataName data:(NSData *)datas{
     [self createClientTcpSocket];//发图片
     [_asyncsocket writeData:datas withTimeout:-1 tag:0];

   }
过去多啦不再A梦过去多啦不再A梦2809 days ago627

reply all(2)I'll reply

  • 漂亮男人

    漂亮男人2017-05-02 09:36:17

    The information is not complete and it is difficult to judge the reason, but in this case, the for loop should be put inside
    Also, a lock should be added when accessing resources

    dispatch_async(queue, ^{
        for (int i =0; i < 10; i++) {
            // upload ....
        }
    })

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-02 09:36:17

    The code and logs are incomplete and I can’t see why. Guess two reasons:

    1. In fact, it still works, but you can’t catch the status due to debugging issues

    2. It was really interrupted. The specific reason needs to be investigated in depth. However, it is recommended that you use queue as a reference and hold it for a long time, not as a local variable. If it is a local variable, what is the point of making a serial queue?

    reply
    0
  • Cancelreply