的是Android上下文线程安全的? [英] Is Android Context thread safe?

查看:149
本文介绍了的是Android上下文线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用的AsyncTask#doInBackground内Android的背景下,它是线程安全的?上下文是通过构造函数或通过getApplicationContext()从周围的活动提供。这个简单的问题被问了很多在计算器和其他地方,但我发现没有一个明确的答案?

When I use the Android Context within an AsyncTask#doInBackground, is it thread safe? The context is provided via constructor or via getApplicationContext() from a surrounding Activity. This simple questions is asked a lot at stackoverflow and else where but I found not a clear answer?

例如。在doInBackground()我使用的背景下,以实例化一个DAO类。

E.g. in the doInBackground() I use the context in order to Instantiate an DAO class.

 @Override
 protected Void doInBackground(Void... params) {  

   ExampleDao dao = new ExampleDao(context);
   ...

 }

我看见几个例子做的,通过这种方式,但我无法想象这是线程安全的,因为上下文现在由主胎面(UI线程)和辅助线程访问。

I saw several examples doing that in this way, but I cannot image that this is thread-safe, because the context is now accessed by the main tread (UI Thread) and the worker thread.

推荐答案

您可以随时访问不同线程的上下文,只要你不改变的东西,你只能通过上下文检索资源,我看不出有问题线程安全。

You can always access the context from different Thread as long as you are not changing something and you only retrieve resources through the context I don't see a problem with Thread-safety.

的问题是,在上下文将只要留在存储器和活跃线程运行。这是一件好事,因为你可以依靠有一个有效的上下文的所有时间。
坏事是,​​如果你传递一个活动作为背景全部来自本次活动的意见和成员变量也将保持在内存中,这可能会导致一个非常晚的垃圾收集了很多的记忆,就像Waqas建议。

The problem is that the context will stay in memory and active as long as the Thread runs. This is a good thing for you because you can rely on having a valid context all the time. The bad thing is that if you pass an Activity as a context all the views and member variables from this activity will also stay in memory and this can lead to a very late garbage collection for a lot of memory, like Waqas suggested.

在我就不会从一个不同的线程做的一件事是访问来自上下文子像<一个方法href=\"https://developer.android.com/reference/android/view/ContextThemeWrapper.html#setTheme%28int%29\"相对=nofollow> setTheme(),这将影响当前显示的看法。

On thing I would not do from a different Thread is accessing methods from Context subclasses like setTheme() that will affect the currently displayed views.

这篇关于的是Android上下文线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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