Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the F# equivalent of Task.Delay(-1)?

Does F# have its own equivalent, or is the only equivalent Task.Delay(-1) |> Async.AwaitTask?

like image 560
robbie Avatar asked Oct 28 '25 19:10

robbie


1 Answers

It looks like the Discord bot examples you've been seeing using Task.Delay(-1) are doing the following in the Task:

  1. Set up some event handlers so that when certain events happen, they'll respond
  2. Call Task.Delay(-1) so that the task will run forever (and will handle those events as they come up)

What I think you'll want to investigate is the F# MailboxProcessor class (best introduction, IMHO, is this one). It's designed to be an asynchronous "agent" that runs forever. It has a queue of incoming messages (of whatever type you want), and it will wait for an incoming message, respond to that message, and then "go to sleep" again (not blocking a thread) until another incoming message arrives. All you need to do is to hook up the events of the DiscordClient object to functions that will post appropriate messages to your MailboxProcessor.

Then instead of starting a Task that uses Task.Delay(-1), your main function in Program.fs can just start the MailboxProcessor, set up a WaitHandle, and then call .WaitOne() on it, which will have the same effect: waiting forever (without being in an infinite loop, so you don't run your CPU at 100%) so your bot program doesn't exit.

And that design also allows you to incorporate a "quit" command into your bot: the MailboxProcessor will be set up so that when that "quit" command arrives, it will do any shutdown procedure it needs to, then signal the WaitHandle to tell the main program that it's time to quit. The main program will then exit the .WaitOne() call, and exit. (Exiting the main program will also automatically shut down any async processes still running, BTW).

Using this design — a MailboxProcessor that runs forever, and a WaitHandle that it signals when it's time for the main program to quit — feels more like idiomatic F# to me than using Task.Delay(-1) |> Async.AwaitTask.

like image 117
rmunn Avatar answered Oct 30 '25 15:10

rmunn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!