views:

53

answers:

1

Hi there,

I've a two while loops, which I will have run parallel with the TPL.

My code :

public void Initialize()
{
   cts = new CancellationTokenSource();

   ParallelOptions options = new ParallelOptions();
   options.CancellationToken = cts.Token;
   options.MaxDegreeOfParallelism = Environment.ProcessorCount;

    task = Task.Factory.StartNew(() => Parallel.Invoke(options, Watcher1, Watcher2), cts.Token);
}

public void Watcher1()
{
   //Can I replace this (with a TPL construct in the initialize method)?
   while(true)
   {
      //Do sth.
   }
}

public void Watcher2()
{
   //Can I replace this (with a TPL construct in the initialize method)?
   while(true)
   {
      //do sth 
   }
}

It would be nice, if I can cancel this two actions safely. Can you give me some advices?

Thanks in advance.

Kind regards, pro

+2  A: 

You can do it using a CancellationTokenSource, see this article for details

Thomas Levesque