1

I have an Activity which runs a number of separate downloading tasks on different threads. They are creating in onCreate() like this:

public override void OnCreate()
{
    base.OnCreate();
    workerThread = new Thread(() =>
    {
        InitialiseDownloads();
        foreach (DownloadingFile file in downloadingFiles)
            {
                Thread t = new Thread(file.StartDownload);
                threads.Add(t);
                t.Start();
            }
    });
    workerThread.Start();
}

Where a List<Thread> threads is filled with a new thread for every file to download.

If the activity is closed before these threads finish, will they keep running after the activity is killed if I don't abort them? If so, is this appropriate:

public override void OnDestroy()
{
    workerThread.Abort();
    foreach (Thread thread in threads)
    {
        thread.Abort();
    }
    base.OnDestroy();
}
Moffen
  • 1,817
  • 1
  • 14
  • 34

1 Answers1

2

There's no guarantee your Thread will be killed after Activity is destroyed. It may be killed right short after or it may stay alive as long as the OS allows it to. To make things worse, if you leak your Activity into your thread it won't be destroyed as long as the thread is running.

If you want your background task to survive even when Àctivity gets killed use a Service. To guarantee it's not killed by the OS you should start it in foreground - startForeground.

Anatolii
  • 14,139
  • 4
  • 35
  • 65
  • Thankyou, some great information here that I needed. In summary though, when I should include this onDestroy() method if I want all threads aborted and garbage collected as the Activity is? – Moffen Oct 18 '18 at 20:31
  • 1
    @Moffen No problem. It depends on how you do the download. If you use `InputStream` for that then you could just close it once you no longer need it. If you download chunk by chunk then you could do it in a `while` loop with some `isDownloading` flag so that to set it to `false` when Àctivity` gets killed. – Anatolii Oct 18 '18 at 20:50