objective-c - GCDAsyncsocket always fails to execute when placed in a child thread. What's going on?
过去多啦不再A梦
过去多啦不再A梦 2017-05-02 09:34:17
0
2
607

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梦

reply all(2)
漂亮男人

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 ....
    }
})
大家讲道理

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?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template