title: How to restart System.Threading.Tasks.Task in C#
body: <p>I'm working on an application where i've a task that can be stopped &amp; restarted later.
  for that i've two methods: </p>
  
  <pre><code>public static void TaskProcess()
      {
          var tokenSource = new CancellationTokenSource();
          CancellationToken token = tokenSource.Token;
          var task = new Task(
              () =&gt;
                  {
                      DoWork(token);
                  }, 
              token);
  
          task.ContinueWith(
              task1 =&gt;
                  {
                      Console.WriteLine("Task finished... press any key to continue");
                      Console.ReadKey();
                      Console.WriteLine("Press q to quit...");
                  },
              token);
  
          task.Start();
  
          string input;
          while ((input = Console.ReadLine()) != "q")
          {
              if (input == "c")
              {
                  tokenSource.Cancel();
              }
              if (input == "r")
              {
                  if (task.IsCompleted)
                  {
                      // Here i want to restart my completed task
                  }
                  else
                  {
                      Console.WriteLine("Task is not completed");
                  }
              }
          }
      }
  
      private static void DoWork(CancellationToken token)
      {
          int i = 0;
          while (true)
          {
              i++;
              Console.WriteLine("{0} Task continue...", i);
              Thread.Sleep(1000);
  
              if (token.IsCancellationRequested)
              {
                  Console.WriteLine("Canceling");
                  token.ThrowIfCancellationRequested();
              }
          }
      }
  </code></pre>
  
  <p>Currently, i create new instance of Task and CancellationToken to "restart" the task but i'm looking for something better if possible:</p>
  
  <pre><code>if (input == "r")
              {
                  if (task.IsCompleted)
                  {
                      Console.WriteLine("Task is completed... Restarting");
                      tokenSource = new CancellationTokenSource();
                      token = tokenSource.Token;
                      CancellationToken token1 = token;
                      task = new Task(
                          () =&gt; DoWork(token1),
                          token);
                      task.Start();
                  }
                  else
                  {
                      Console.WriteLine("Task is not completed");
                  }
              }
  </code></pre>
  
  <p>Thanks for your help.</p>