开发者

Should my block based methods return on the main thread or not when creating an iOS cloud integration framework?

开发者 https://www.devze.com 2023-04-12 13:04 出处:网络
I am in the middle of creating a cloud integration framework for iOS. We allow you to save, query, count and remove with synchronous and asynchronous with selector/callback and block implementations.

I am in the middle of creating a cloud integration framework for iOS. We allow you to save, query, count and remove with synchronous and asynchronous with selector/callback and block implementations. What is the correct practice? Running the completion blocks on the main thread or a backgroun开发者_StackOverflowd thread?


For simple cases, I just parameterize it and do all the work i can on secondary threads:

  • By default, callbacks will be made on any thread (where it is most efficient and direct - typically once the operation has completed). This is the default because messaging via main can be quite costly.

  • The client may optionally specify that the message must be made on the main thread. This way, it requires one line or argument. If safety is more important than efficiency, then you may want to invert the default value.

  • You could also attempt to batch and coalesce some messages, or simply use a timer on the main run loop to vend.

  • Consider both joined and detached models for some of your work.

If you can reduce the task to a result (remove the capability for incremental updates, if not needed), then you can simply run the task, do the work, and provide the result (or error) when complete.


Apple's NSURLConnection class calls back to its delegate methods on the thread from which it was initiated, while doing its work on a background thread. That seems like a sensible procedure. It's likely that a user of your framework will not enjoy having to worry about thread safety when writing a simple callback block, as they would if you created a new thread to run it on.

The two sides of the coin: If the callback touches the GUI, it has to be run on the main thread. On the other hand, if it doesn't, and is going to do a lot of work, running it on the main thread will block the GUI, causing frustration for the end user.

It's probably best to put the callback on a known, documented thread, and let the app programmer make the determination of the effect on the GUI.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号