结合ManualResetEvent和token.WaitHandle.WaitOne

nuc*_*eet 3 .net c# multithreading task

我有:

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

所以我在new中启动这个方法Task并在循环中做一些工作,直到我需要取消它token 有时我需要强制新的循环迭代,而不是等待这67秒.我想我需要这样的东西:

public ManualResetEvent ForceLoopIteration { get; set; }
Run Code Online (Sandbox Code Playgroud)

同时我无法理解如何使用令牌.也许是这样的WaitHandle.WaitAny()

abt*_*bto 11

你是正确的方式,试试这个:

WaitHandle.WaitAny(
    new[] { token.WaitHandle, ForceLoopIteration },
    TimeSpan.FromSeconds(67));
Run Code Online (Sandbox Code Playgroud)

这等待出现以下之一

  • 要求取消 token
  • ForceLoopIteration 已设定
  • 已超过67秒的超时时间