I am new in Windows Phone development and I am trying to create a windows phone app using C#
Thread t = new Thread(doaheavywork);
t.Start();
if (!t.Join(1000)) // give the operation 1s to complete
{
t.Abort();
}
I cannot alter the doaheavywork function.
I just need the result to be omputed within 1 or 2 seconds, since sometimes it may run for very long time.
I have read using abort is the wrong way.
I am using the above in a PhotoChooserTask complete function. First run executes fine. That is, when I click the button to select a photo, the doaheavywork function doesn't exceed 1 sec. But if I try for the second time, the PhotoChooserTask just throws an exception and stops.
Is it because I aborted the process in 1st run? Or anything else? Is there any other way to do it?
.Abort()
causes the thread to be destroyed completely. If you are generating a new thread each time like in your example, then it will work. However if you are using the samet
object, then you need to create a new thread object, you can't run.Start()
on an aborted thread.However the fact you are aborting a thread is a concern. What happens with the application when it does take more than 2 seconds. Should you be showing the user, please wait, its taking longer than expected. Doing that in the
if
block is where to do it..Join()
won't stop the thread even if it doesn't manage to join.Edit
You have 2 options you might want to consider in rewriting this section:
Tasks seem to be the appropriate solution in your scenario.