objective-c - GCDAsyncsocket 放到子线程总会不不执行,这是怎么回事
过去多啦不再A梦
过去多啦不再A梦 2017-05-02 09:34:17
0
2
534

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梦

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!