委托dispatch_queues中的回调 [英] Delegate callbacks in dispatch_queues

查看:57
本文介绍了委托dispatch_queues中的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据

According to the AWS SDK documentation, the following will not work:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{

    S3PutObjectRequest *request = [[S3PutObjectRequest alloc] initWithKey:objectKey inBucket:bucketName];
    request.data = data;
    request.delegate = self;

    [s3Client putObject:request];
});

的意思是,由于以下原因,将不会调用委托方法:

meaning, the delegate methods will not be called, due to the following reason:

此GCD队列中的块将在后台线程中执行,它有自己的运行循环,与主线程分开.委托将在后台线程的运行循环中注册负责调用AmazonServiceRequestDelegate方法.但是,putObject:立即返回,整个块也返回.当块完成执行时,背景线程将由GCD收集,没有任何责任调用委托方法将被遗忘.这就是为什么上面代码示例不起作用.

The block in this GCD queue will be executed in the background thread, which has its own run loop, separate from the one on the main thread. The delegate will be registered with the background thread's run loop that is responsible for calling the AmazonServiceRequestDelegate method. However, putObject: immediately returns and the entire block also returns. When the block finishes its execution, the background thread will be collected by GCD, and nothing that is responsible for calling the delegate methods will be left behind. That's why the above code sample doesn't work.

是的,从不为该代码块调用委托方法.但是,我希望它能起作用:

And it's true, the delegate methods are never called for that block of code. However, I expected this to work:

self.queue = dispatch_queue_create("MyQueue", NULL);
dispatch_async(self.queue, ^{

    S3PutObjectRequest *request = [[S3PutObjectRequest alloc] initWithKey:objectKey inBucket:bucketName];
    request.data = data;
    request.delegate = self;

    [s3Client putObject:request];
});

请注意,我保留了队列,因此在块返回后,队列仍然存在.但是,这仍然行不通-永远不会调用委托回调.为什么会这样?

Notice that I'm retaining the queue, so after the block returns, the queue sticks around. However, this still doesn't work - the delegate callbacks are never called. Why is this so?

推荐答案

您已经创建了一个串行调度队列,但这并不意味着应该有一个附加到该队列的线程,系统管理器,后台线程以及它.将为某个队列提供一个线程,以执行您推送到该队列的代码.

You have created a Serial Dispatch Queue, but it doesn't mean that there should be a thread attached to the queue, the system manager the background thread and it will provide a thread to some queue to execute the code you push to the queue.

串行调度队列保证您推送到它的工作被一个接一个地执行,但不能保证完成工作的线程是相同的.

The Serial Dispatch Queue guarantee the works you push to it is executed one by one but it doesn't guarantee the thread which do the work is the same.

因此,在使用全局并发调度队列时,您会遇到相同的问题.

So you face the same problem when using Global Concurrent Dispatch Queues.

这篇关于委托dispatch_queues中的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆