0

My application contains a long loop which calculates many values within my UIThread and subsequently draws them onscreen.

If I were to offload the calculation loop onto a separate thread using AsyncTask, I would be unable to run MyAsyncTask.execute() multiple times as according to the documentation: "The task can be executed only once". When I attempted to run the code I was able to see a single frame drawn but then an exception was thrown: "Cannot execute the task: the task has already been executed (a task can be executed only once)".

It would not be a good idea to create a new AsyncTask object during each iteration of the draw loop, so is there any way to reuse the same AsyncTask object to run MyAsyncTask.execute() again? Or if not, what would be a more appropriate method to use? Can other forms of threads achieve this?

Jaween
  • 374
  • 1
  • 3
  • 10
  • What exactly do you do in that for loop? – user Oct 02 '12 at 12:35
  • 1
    why wouldn't it be a good idea to create new task for each iteration ? also, why don't you do the loop inside the asynctask ? it takes an array of items as parameter – njzk2 Oct 02 '12 at 12:38
  • @Luksprog It evaluates a postfix maths expression (such as 5, 7, *). It repeats the process a few hundred times with different values and seems to be quite slow. – Jaween Oct 02 '12 at 12:56
  • @njzk2 I would be allocating memory to create a new object each time the screen is drawn to, thus causing rapid garbage collection. Or am I mistaken? I am trying to do the calculations loop inside the AsyncTask. I essentially tell the loop how many times it needs to iterate, the thread does its separate thing and it returns an array of the answers – Jaween Oct 02 '12 at 12:56

1 Answers1

2

Create AsyncTask class object each time when you want to excute.

Example

    Task _task=new Task();
    _task.excute();

For More Info Read This Tutorial Link

Community
  • 1
  • 1
Rishabh Agrawal
  • 861
  • 2
  • 15
  • 25