Reputation: 582
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?
Upvotes: 0
Views: 1241
Reputation: 16199
.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 same t
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.
Upvotes: 3
Reputation: 3216
One approach maybe be to consider using a Task and having a CancellationToken passed in to it from a CancellationTokenSource instantiated against a specific timespan - 2 seconds. That way when the the time specified has elapsed, the CancellationToken, passed to the Task, will be signaled and then appropriate action can be taken.
Upvotes: 1