【问题标题】:Is there a chance to replace a while loop with the TPL?是否有机会用 TPL 替换 while 循环?
【发布时间】:2021-07-24 14:08:24
【问题描述】:

我有两个 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 
   }
}

如果我能安全地取消这两个动作就好了。能给我一些建议吗?

提前致谢。

亲切的问候,亲

【问题讨论】:

    标签: c# .net-4.0 parallel-processing task-parallel-library


    【解决方案1】:
    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
       }
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用CancellationTokenSource 进行操作,详情请参阅this article

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-01-21
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 2021-05-03
        • 1970-01-01
        • 2011-12-07
        相关资源
        最近更新 更多