简体   繁体   English

F# 线程中的取消令牌

[英]cancellation token in F# threads

I am struggling with the following:我正在努力解决以下问题:

I have a system that has its main flow and has two background threads that can be started and stopped, but they're generally very long running as they stop only during configuration changes.我有一个系统,它有它的主要流程,并且有两个可以启动和停止的后台线程,但它们通常运行时间很长,因为它们只在配置更改期间停止。

I found that the cancellation token in F# gets checked at async points in the code.我发现在代码中的异步点检查了 F# 中的取消令牌。 The worker threads do not perform any async operations;工作线程不执行任何异步操作; they are doing background work but nothing is asynchronous.他们正在做后台工作,但没有什么是异步的。

A simplified version looks like that:简化版本如下所示:

let workerThread (someParameters) =
    async {
        while true do
            setup some event driven system that has a callback when work is finished
            on callback, signal
            waitHandle.WaitOne()                
}

and it gets started like this:它开始是这样的:

Async.StartAsTask(workerThread parameter, cancellationToken = cancellationSource.Token)

Since there is absolutely nothing async in the system, the cancellation token will never be checked and, besides, I need to be able to manually check it in the event driven systems that keep getting set up by the two worker threads.由于系统中绝对没有任何异步,因此永远不会检查取消令牌,此外,我需要能够在由两个工作线程不断设置的事件驱动系统中手动检查它。

How can this be done?如何才能做到这一点? In C# the token is passed directly and I can check it whenever I feel like.在 C# 中,令牌是直接传递的,我可以随时检查它。

F# propagates cancellation token to the task which is created, but if worker function is blocked while waiting for a handle it cannot check the cancellation token. F# 将取消令牌传播到创建的任务,但如果工人 function 在等待句柄时被阻止,则无法检查取消令牌。 To solve this issue you should wait for the cancellation token wait handle as well:要解决此问题,您还应该等待取消令牌等待句柄:

let workerThread () =
  async {
      let! token = Async.CancellationToken // this way you can get cancellation token
      while true do
          // whatever
          WaitHandle.WaitAny([| waitHandle; token.WaitHandle |]) |> ignore
  }

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

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