2

2つのwhileループがあり、TPLと並行して実行します。

私のコード:

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 
   }
}

この2つのアクションを安全にキャンセルできればいいのですが。アドバイスをいただけますか?

前もって感謝します。

よろしく、プロ

4

2 に答える 2

2
public void Initialize()
{
   var cancellationSource = new CancellationTokenSource();
   var cancellationToken = cancellationSource.Token;

   //Start both watchers
   var task1 = Task.Factory.StartNew(() => Watcher1(cancellationToken));
   var task2 = Task.Factory.StartNew(() => Watcher2(cancellationToken));

   //As an example, keep running the watchers until "stop" is entered in the console window
   while (Console.Readline() != "stop")
   {
   }

   //Trigger the cancellation...
   cancellationSource.Cancel();

   //...then wait for the tasks to finish.
   Task.WaitAll(new [] { task1, task2 });
}

public void Watcher1(CancellationToken cancellationToken)
{
   while (!cancellationToken.IsCancellationRequested)
   {
      //Do stuff
   }
}

public void Watcher2(CancellationToken cancellationToken)
{
   while (!cancellationToken.IsCancellationRequested)
   {
      //Do stuff
   }
}
于 2012-12-16T06:18:50.370 に答える
2

を使用して実行できます。詳細については、この記事を参照してくださいCancellationTokenSource

于 2010-09-29T16:08:23.430 に答える