Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restart a completed task

Tags:

c#

task

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?

like image 273
Mohamad MohamadPoor Avatar asked Jul 16 '14 21:07

Mohamad MohamadPoor


2 Answers

Stephen Taub explains it (I can actually recommend reading more of his articles regarding Tasks)

  1. 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

like image 98
default Avatar answered Nov 04 '22 00:11

default


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).

like image 41
Haney Avatar answered Nov 04 '22 00:11

Haney