Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 是否有机会用TPL替换while环路?_C#_.net 4.0_Parallel Processing_Task Parallel Library - Fatal编程技术网

C# 是否有机会用TPL替换while环路?

C# 是否有机会用TPL替换while环路?,c#,.net-4.0,parallel-processing,task-parallel-library,C#,.net 4.0,Parallel Processing,Task Parallel Library,我有两个while循环,我将与TPL并行运行 我的代码: public void Initialize() { cts = new CancellationTokenSource(); ParallelOptions options = new ParallelOptions(); options.CancellationToken = cts.Token; options.MaxDegreeOfParallelism = Environment.ProcessorCo

我有两个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 
   }
}
如果我能安全地取消这两个动作,那就太好了。你能给我一些建议吗

提前谢谢


问候您,pro

您可以使用
取消令牌源来完成此操作,有关详细信息,请参阅

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