何时线程。何时不使用线程
我对线程的想法很陌生,但对异步行为并不陌生。我的 Android 应用程序启动时间约为 180 毫秒,当我使用 GoogleAnalytics trackViewPage 方法和 MobFoxView 构造函数时,启动时间约为 550 毫秒。从 Actionscript 3 开始,任何“需要时间”的事情都会自动异步,我被迫用监听器来处理它,这在 Android 中似乎有点不同。看起来我负责决定什么时候应该异步。所以我想我的问题是,如何我决定什么应该是异步的?是按毫秒执行吗?但也许不同设备之间的情况会有很大变化。或许应该是由……或者是由……?
I'm new to the idea of Threading, but not asynchronous behavior. My Android app is taking ~180 millisecond to start up and ~550 milli when I use GoogleAnalytics trackViewPage method and MobFoxView constructor. Coming from Actionscript 3, anything that "took time" was automatically async and I was forced to handle it with listeners which is a bit different in Android it appears. It seems I'M responsible for deciding when something should be asynchronous. So I guess my question is, HOW do I decide what should be async? Is it by milliseconds of executing? But perhaps that changes greatly between devices. Perhaps it should be by ... or is it by ....?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要知道一件重要的事情 - 默认情况下,您在不启动单独线程的情况下所做的所有操作都在“主”线程(也称为 UI 线程)上执行。
如果你做了一些可能会阻塞的事情——你的用户界面将会滞后,用户将会受到影响。
如果你做的事情与 UI 无关,而是与数据库查询、网络调用或潜在的长时间阻塞操作有关 - 你需要直接启动线程或使用 AsyncTask。
另外您必须注意,如果您尝试从非主线程对 UI 执行某些操作(例如将值设置为 TextView),您将会失败。 UI 只能从 UI-Thread 访问。
You need to know one important thing - by default everything you do without starting separate thread is executed on "main" thread (also knows as UI-thread).
If you do something, which can block - your UI will lag and users will suffer.
If you doing something, which is not about UI but about database query, network call or potentially long blocking operation - you need to start thread directly or use AsyncTask.
Also you must note, if you try to do something with UI (e.g. set value to a TextView) from not-main thread you will fail. UI can be acessed only from UI-Thread.