结合ManualResetEvent和token.WaitHandle.WaitOne

时间:2014-05-14 10:36:19

标签: c# .net multithreading task

我得到了:

internal void Start(CancellationToken token)
{
   while (!token.IsCancellationRequested)
   {
       //do work
       token.WaitHandle.WaitOne(TimeSpan.FromSeconds(67));
   }       
}

所以我在新Task中启动此方法并在循环中完成一些工作,直到我需要使用token取消它 有时我需要强制进行新的循环迭代,而不是等待这67秒。 我想我需要这样的东西:

public ManualResetEvent ForceLoopIteration { get; set; }

同时我无法理解如何将它与令牌一起使用。 也许像WaitHandle.WaitAny()这样的东西?

1 个答案:

答案 0 :(得分:11)

你走对了路,试试这个:

WaitHandle.WaitAny(
    new[] { token.WaitHandle, ForceLoopIteration },
    TimeSpan.FromSeconds(67));

等待以下

之一出现
  • 取消token
  • ForceLoopIteration已设置
  • 超时67秒已经过去