简体   繁体   English

榆木并发

[英]Concurrency in Elm

I have a really computationally expensive code that I need to run in my 'update' function. 我有一个计算量很大的代码,需要在“更新”功能中运行。

When it runs, my whole app blocks until it finishes. 当它运行时,我的整个应用程序都会阻塞,直到完成为止。

Is there any way to run this code asynchronously to prevent the blocking? 有什么办法可以异步运行此代码以防止阻塞? (while not using ports and staying in elm) (同时不使用端口并留在榆树中)

Elm tasks do not support pre-emptive multi-tasking. 榆树任务不支持抢先式多任务处理。

With Process.spawn , you can construct tasks which will context-switch when used as arguments to Task.andThen . 使用Process.spawn ,您可以构造将用作Task.andThen参数时上下文切换的任务。

However, for those, you have to work within the constraint that the resulting task has type Task x Process.Id , which means there is no easy way to communicate the result of your task back to the main app. 但是,对于这些应用程序,您必须在结果任务的类型为Task x Process.Id的约束下进行工作,这意味着没有简单的方法可以将任务的结果传达回主应用程序。

See the documentation for Process.Id . 请参阅Process.Id 的文档

You can try to run it as a Task. 您可以尝试将其作为任务运行。 Tasks can be preemptively be stopped to execute other parts of your application, although I'm unsure how they will work in the case of some using the entirety of the CPU capacity: 可以抢先停止任务以执行应用程序的其他部分,尽管我不确定在某些使用全部CPU容量的情况下它们如何工作:

DoHeavyStuff a b ->
    let
        task param1 param2 =
            Task.succeed 1
            `Task.andThen` (\_ -> Task.succeed <| expensive param1 param2)
    in
    (model, Task.perform NoOp FinishedWork (task a b))

FinishedWork result ->
    ...

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

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