Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
685 views
in Technique[技术] by (71.8m points)

events - what is the best way to get notified when a task finishes, in F#?

I have a pool of tasks and I am trying to figure out the best way to be notified, through an event, when one is finished.

Since the tasks are quite varied, I don't want to add a piece of code inside the task itself since that would mean putting it in several places. These are long running tasks, I'm not waiting for them to complete anywhere, they're just getting started, do their work (minutes to days) and then they finish.

The ugly-but-could-work solution is to wrap each work task into another task that awaits for the work task to be complete and then sends an event, but I'm hoping there would be something more elegant.

question from:https://stackoverflow.com/questions/66060890/what-is-the-best-way-to-get-notified-when-a-task-finishes-in-f

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In a comment you explained that you're starting your tasks like this:

Async.StartAsTask (runner.Start(), TaskCreationOptions.LongRunning, cancellationSource.Token)

Instead of doing that, start them like this:

startMyTask runner cancellationSource (fun() -> printfn "Task completed!")

Where:

let startMyTask (runner: RunnerType) (s: CancellationTokenSource) onDone = 
    let wrapper = async { 
      do! runner.Start()
      onDone() 
    }
    Async.StartAsTask (wrapper, TaskCreationOptions.LongRunning, s.Token)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...