【问题标题】:Android Task Threads and the UIAndroid 任务线程和 UI
【发布时间】:2014-04-02 14:18:35
【问题描述】:

我正在尝试在后台/异步/...中运行大型 XML 文件的导入 - 换句话说,我正在尝试将其从 UI 线程中移除。

我的代码如下:

private string ImportXML()
    {
        string returnFile = null;
        ParseXML.ParseXML parsexml = new ParseXML.ParseXML (chosenFile);

        ProgressDialog progress = new ProgressDialog(this);
        progress.SetMessage(GetString(Resource.String.ImportXML));
        progress.Indeterminate = true;
        progress.Show();

        Task xmlTask = new Task (() => returnFile = parsexml.ProcessXML());

        xmlTask.Start();

        while (!(xmlTask.IsCompleted || xmlTask.IsCanceled || xmlTask.IsFaulted))
            progress.Show();

        xmlTask.Wait(); 

        progress.Hide();

        return returnFile;
    } 

代码似乎正在同步运行或仍在主 UI 线程中运行,因为 UI 更新(我暂时尝试使用 while 循环)没有发生 - 我看不到进度全部。

该操作可能需要几秒钟 - 对于我的一些示例文件最多需要 10 秒钟 - 所以我不热衷于使用 AsyncTask,因为我认为它不建议用于长时间的操作。

谁能告诉我这哪里出了问题?

【问题讨论】:

  • 使用异步任务,非常适合。您确定您的代码在单独的线程中运行吗?我的意思是ImportXML() 方法是在单独的线程中运行吗?
  • 当然,您不会看到使用 NON-UI 线程来更新进度的更新...您必须调用 UI 线程来执行此操作。
  • @XaverKapeller 感谢您的回复。我对 Android(和 c#)开发有点陌生,所以我的印象是,通过以这种方式调用 ImportXML,我会强制它位于单独的线程中。从你的回复我猜不是这样?
  • 不,不是。我将发布一个带有示例的答案AsyncTask。

标签: c# android multithreading asynchronous


【解决方案1】:

我创建了一个示例AsyncTask 来向您展示如何处理与 ui 线程分开的数据。这个AsyncTask 将从资源中加载String 并将其设置为TextView。

重要提示:通常您永远不需要AsyncTask 来从资源中加载String。我只是选择这个作为示例来展示如何在单独的线程中执行工作。

对于任何AsyncTask,只需记住一件事:您在单独的线程中执行工作,而不是在 ui 线程中。当单独的线程完成时,无法保证您引用的 ui 元素仍然存在,甚至您的应用程序仍在运行。因此,如果您引用 Activity 或 Context 或某些 ui 元素,如 TextView 或 Button 或任何其他在后台线程完成时可能不再存在的复杂对象,您必须使用 WeakReference . WeakReferences 是解决此问题的一种巧妙方法,它允许对您引用的对象进行垃圾收集。然后,在您的AsyncTask 中,您可以检查您需要的对象是否仍然存在,如果是,则执行您的工作而不会造成内存泄漏。你像这样使用WeakReference:

WeakReference<TextView> textViewReference = new WeakReference<TextView>(textView);

如您所见,WeakReference 是一个泛型类型。如果您想在这种情况下引用TextView,您必须通过在WeakReference 之后写&lt;TextView&gt; 来告诉WeakReference。如果您要引用Context,则应写为WeakReference&lt;Context&gt;,或者如果您引用SQliteDatabase,则应写为WeakReference&lt;SQLiteDatabase&gt;。我猜你看到了这里的模式。
您将要引用的对象的实例传递给WeakReference 的构造函数。这就是上面示例的(textView) 部分。如果您以后想从WeakReference 取回实例,您可以这样做:

TextView textView = textViewReference.get();

如果您引用的 TextView 不再存在,get() 将简单地返回 null。因此,要检查 TextView 是否仍然存在,您可以简单地这样做:

TextView textView = textViewReference.get();
if(textView != null) {
   // TextView still exists. 
} else {
   // TextView doesn't exist anymore. Most likely he has already been garbage collected.
}

如果您了解有关如何以及何时使用WeakReferences 的简单原则,那么实现AsyncTask 应该没有问题。我已经用 cmets 解释了有关 AsyncTask 的任何其他重要信息,只需查看源代码即可。如果您有任何其他问题,请随时提出。

public class ExampleTask extends AsyncTask<Void, Void, String> {

    // We use WeakReferences for all complex objects to prevent memory leaks
    private final WeakReference<TextView> textViewRefernece;
    private final WeakReference<Context> contextReference;

    // Primitives are fine. WeakReferences are not needed here.
    private int resourceId;

    public ExampleTask(Context context, TextView textView, int resourceId) {

        // We create the WeakReferences to our Context and to the TextView in which we want the result to appear.
        this.contextReference = new WeakReference<Context>(context);
        this.textViewRefernece = new WeakReference<TextView>(textView);

        this.resourceId = resourceId;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

        // This method is executed on the ui thread just before the background thread starts.
        // You can perform some inital setup here but mostly you can leave this empty
    }

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

        // This method is executed in a background thread. Here we can do our work.
        // First we have to get the context from the WeakReference
        Context context = contextReference.get();

        // Now we check if the Context still exists. If the context is null it has already been garbage collected.
        // That would happen for example if the app has been closed or even if it crashed.
        if(context != null) {

            // The context is not null which means it still exists we can continue and load the required String and return it
            return context.getString(this.resourceId);
        }

        // If something went wrong we return null.
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        // This method is executed on the ui thread after the background thread is finished.
        // Here we get our final result and can set it to our TextView

        // First we check if the String result is null. If it is not null the background thread has finished successfully and we can continue.
        if(result != null) {

            // Here we get our TextView from the WeakReference
            TextView textView = textViewRefernece.get();

            // Now we check if the TextView still exists. If it is null it has already been garbage collected.
            // That would happen for example if the app has been closed while the AsyncTask has been running.
            // Or simply if the Fragment has been replaced or the Activity has changed.
            if(textView != null) {

                // The TextView is not null which means it still exists. We can now set our text.
                textView.setText(result);
            }
        }
    }
}

【讨论】:

  • 问题标记为 C#,而不是 Java。这是 Java 代码。
  • 我没看清楚这个问题。他从未提到他正在使用 Xamarin 或类似的东西。但是,一旦你在get() 之后持有引用,它就不能再被垃圾收集,因为你再次直接持有引用。
  • 谢谢@XaverKapeller - 很抱歉我没有更详细地解释我正在使用 Xamarin 和 C#。在尝试您给我的异步任务示例之前,我将尝试 Servy 给出的 C# 示例。
【解决方案2】:

是的,您创建一个任务来在非 UI 线程中完成一些工作。然后你告诉 UI 线程坐在那里等待其他任务完成。在完成该任务之前,您不要让它继续进行或做任何其他工作。这会阻塞 UI 线程,并且只在 UI 线程中完成工作并不比这更好(开销实际上使情况变得更糟)。

您需要做的是向任务添加一个延续,它可以在任务完成时处理您想做的任何工作,然后让方法结束,以便 UI 线程可以继续做其他工作。

private Task<string> ImportXML()
{
    ParseXML.ParseXML parsexml = new ParseXML.ParseXML(chosenFile);

    ProgressDialog progress = new ProgressDialog(this);
    progress.SetMessage(GetString(Resource.String.ImportXML));
    progress.Indeterminate = true;
    progress.Show();
    var task = Task.Factory.StartNew(() => parsexml.ProcessXML());
    task.ContinueWith(t => progress.Hide());
    return task;
}

因为这个方法必须是异步的,允许 UI 线程继续工作,它需要返回一个Task,而不是实际的字符串。然后,此方法的调用者可以在此方法调用的结果中添加一个延续以使用结果。

【讨论】:

  • @XaverKapeller 所以它使用的是 C# 1.0?为什么 lambda 不能工作?
  • 谢谢@Servy - 我已经对我的 ImportXML 方法进行了这些修改以使其成为一项任务。在调用此任务的方法中,我有以下内容: if (chosenFile.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) dbFile = ImportXML().Result;但是通过跟踪这一点,我似乎再次通过这样做来阻塞线程。
  • @Yromulus 没错; Result 阻塞直到有结果。您应该将需要使用此任务本身的结果的工作作为此方法任务的延续。这就是拥有异步程序的意义。
  • 感谢@Servy - 有了您的建议和更多研究,我现在有了一个可行的解决方案 - 非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多