I have a Task that run periodically in the background of my application. When I run it for the first time everything is ok and the Task run to end perfectly. But for the second time and after that whenever I use task.Start()
it throws an exception:
An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll Additional information: Start may not be called on a task that has completed.
I am sure that my task function ran to the end.. what should I do to run the task periodically?
Stephen Taub explains it (I can actually recommend reading more of his articles regarding Tasks)
- Question: Can I call Start more than once on the same Task?
No. A Task may only transition out of the Created state once, and Start transitions a Task out of the Created state: therefore, Start may only be used once. Any attempts to call Start on a Task not in the Created state will result in an exception. The Start method employs synchronization to ensure that the Task object remains in a consistent state even if Start is called multiple times concurrently… only one of those calls may succeed.
.. Which is what you see as well. You can use for instance a timer and start a new Task each time.
If you need to check that only one run at a time, you can check for TaskStatus.RanToCompletion
on the task that is currently running
Take a look at System.Threading.Timer
which lets you execute a callback method periodically. It's great for things that need to run hourly, repeatedly, etc. Don't forget to lock the callback method body if you need to ensure that the timer only ever runs synchronously (in case runs overlap).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With