架构设计中避免在后台线程上调用UI API的正确方法是什么? [英] What's the proper way in architecture design to avoid UI API to be called on a background thread?

查看:88
本文介绍了架构设计中避免在后台线程上调用UI API的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在MacOS应用中,我有另一个模块调用的回调函数(该模块是从Internet获得一些响应以触发回调的网络模块):

In a MacOS app, I have a callback function called by another module (which is a network module that gets some response from the Internet to fire the callback):

func callbackHandler() {
    someViewController.updateSomeView()
}

在此回调处理程序中,将调用一个视图控制器来更新某些视图,并在该视图控制器内重新加载表的数据:

In this callback handler, a view controller is called to update some view, and inside the view controller, reload data for a table:

func updateSomeView() {
    someTable.reloadData()
}

但是,这样做,我将得到如下错误:

However, by doing so, I will get an error like this:

Main Thread Checker: UI API called on a background thread: ...

因此,我必须在调用方中添加DispatchQueue.main.async():

Therefore, I have to add DispatchQueue.main.async() either in the caller :

func callbackHandler() {
    DispatchQueue.main.async() {
        someViewController.updateSomeView()
    }
}

或被叫方:

func updateSomeView() {
    DispatchQueue.main.async() {
        someTable.reloadData()
    }
}

任何一种方法都可以解决问题.但是我认为让调用者或被调用者意识到被调用的UI API将通过添加DispatchQueue.main.async()作为修复程序而在后台线程上被调用是很奇怪的.

Either way will solve the problem. But I think it's quite weird for the caller or the callee to be aware of that UI API called is going to be called on a background thread by adding DispatchQueue.main.async() as a fix.

如何在设计架构方面以适当的方式做到这一点?

How to do it in a proper way in terms of design architecture?

推荐答案

您正在执行的操作以及该API是完全合理的.异步回调到达后台线程(尤其是与网络连接)时,被调用者必须走出主线程才能触摸用户界面,这是很正常的.别担心,要开心.

What you're doing, and the API, is perfectly reasonable. It is quite normal for asynchronous callbacks to arrive on a background thread (esp. in connection with networking), and for the callee to have to step out to the main thread in order to touch the user interface. Don't worry, be happy.

这篇关于架构设计中避免在后台线程上调用UI API的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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