简体   繁体   English

在PLINQ中取消长时间运行的任务

[英]Cancelling long-running tasks in PLINQ

I am trying to use the NET 4.0 parallel task library to handle multiple FTS queries. 我正在尝试使用NET 4.0并行任务库来处理多个FTS查询。 If the query takes too much time, I want to cancel it and continue forward with processing the rest. 如果查询花费太多时间,我想取消它,然后继续处理其余部分。

This code doesn't stop when one query goes over the threshold. 当一个查询超过阈值时,此代码不会停止。 I think I'm calling it such that the cancel task and time limit is reached for the whole of the process rather than the single transaction. 我认为我这样称呼它是为了在整个过程中而不是单个事务中达到取消任务和时间限制。 If I set the time period to be very small (300ms), then it gets called for all search strings. 如果我将时间段设置为非常短(300ms),则所有搜索字符串都会调用该时间段。

I think I'm missing something obvious .. thanks in advance for any insight. 我想我缺少明显的东西..在此先感谢您的见解。

Additionally, this still doesn't seem to stop the very long query from executing. 此外,这似乎仍不能阻止执行很长的查询。 Is this even the correct way to cancel a long running query once it's been triggered? 这甚至是取消长时间运行的查询后被触发的正确方法吗?

Modified code: 修改后的代码:

CancellationTokenSource cts = new CancellationTokenSource();
CancellationToken token = cts.Token;

var query = searchString.Values.Select(c =>myLongQuery(c)).AsParallel().AsOrdered()
                                        .Skip(counter * numToProcess).Take(numToProcess).WithCancellation(cts.Token);

  new Thread(() =>
  {
     Thread.Sleep(5000);
     cts.Cancel();
  }).Start();

  try
  {
     List<List<Threads>> results = query.ToList();
     foreach (List<Threads> threads in results)
     {
           // does something with data
     }
  } catch (OperationCanceledException) {
     Console.WriteLine("query took too long");
  }   

PLINQ will poll the cancellation token after every some number of elements. 每隔一定数量的元素,PLINQ将轮询取消令牌。 If the frequency of checks is insufficient for your application, make sure all expensive delegates in the PLINQ query regularly call cts.Token.ThrowIfCancellationRequested(). 如果检查频率不足以适合您的应用程序,请确保PLINQ查询中所有昂贵的委托都定期调用cts.Token.ThrowIfCancellationRequested()。

For more details, see this article: http://blogs.msdn.com/b/pfxteam/archive/2009/06/22/9791840.aspx 有关更多详细信息,请参见本文: http : //blogs.msdn.com/b/pfxteam/archive/2009/06/22/9791840.aspx

这只是一个猜测:查询不是惰性的(就像在普通LINQ中一样),因此直到以后才执行,这不是问题吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM