我想等待几个异步任务完成并尝试使用dispatch_group实现它,请参阅apple docs:Concurrency Programming Guide。
但是当我进入调度组时,sendAsynchronousRequest
只是没有返回响应。日志不显示任何错误。谁能告诉我我做错了什么?
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
// get Data from Server
NSString *url = [ConfigurationManager getDomain];
url = [url stringByAppendingString:[NSString stringWithUTF8String:URL_GET_JACKPOT]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setTimeoutInterval:TIMEOUT_INTERVAL];
[request setURL:[NSURL URLWithString:url]];
// not getting response
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)responseCode;
if([httpResponse statusCode] != 200){
NSLog(@"@Error: Error getting %@, HTTP status code %li, Error: %@", url, (long)[httpResponse statusCode], error);
}else{
// process result
}
dispatch_group_leave(group); // this never gets called -> deadlock
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
答案 0 :(得分:0)
我认为class MyWidget(QtGui.QPushButton):
def __init__(self, parent= None):
super(MyWidget,self).__init__(parent)
的响应在主线程上执行,我不在(dispatch_enter的原因)。当我创建自己的sendAsynchronousRequest
对象时,它可以工作。
NSOperationQueue
答案 1 :(得分:0)
是的,正如你所说,尝试使用不同的队列,否则你将陷入僵局。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
dispatch_group_t group = dispatch_group_create();
dispatch_group_enter(group);
// get Data from Server
NSString *url = [ConfigurationManager getDomain];
url = [url stringByAppendingString:[NSString stringWithUTF8String:URL_GET_JACKPOT]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setTimeoutInterval:TIMEOUT_INTERVAL];
[request setURL:[NSURL URLWithString:url]];
// not getting response
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)responseCode;
if([httpResponse statusCode] != 200){
NSLog(@"@Error: Error getting %@, HTTP status code %li, Error: %@", url, (long)[httpResponse statusCode], error);
}else{
// process result
}
dispatch_group_leave(group); // this never gets called -> deadlock
}];
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
});