Home  >  Q&A  >  body text

objective-c - GCDAsyncsocket 放到子线程总会不不执行,这是怎么回事

GCDAsyncsocket 使用异步串行子线程中for循环执行一半就不执行了,代码如下,过程是点击发送按钮返回到主页面,然后异步执行下面的代码上传图片;

    
    - (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梦2705 days ago535

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