F# cross-thread UI exception in WinForms App

前端 未结 3 424
盖世英雄少女心
盖世英雄少女心 2021-01-21 09:55

I have a problem with developing a simple application in F#, which just reads the length of the requested HTML page.

Seems to be that such an error would be similar for

3条回答
  •  广开言路
    2021-01-21 10:23

    As an alternative to using the Invoke operation (or context switching) explicitly, you can also start the computation using Async.StartImmediate.

    This primitive starts the asynchronous workflow on a current thread (synchronization context) and then it ensures that all continuations are called on the same synchronization context - so it essentially handles Invoke automatically for you.

    To do that, you do not need to change anything in fetchAsync. You just need to change how the computation is started in runAll:

    let runAll() =
        urlList
        |> Seq.map fetchAsync
        |> Async.Parallel 
        |> Async.Ignore
        |> Async.StartImmediate
    

    Just like before, this composes all of them in parallel, then it ignores the result to get a computation of type Async and then it starts it on a current thread. This is one of the nice features in F# async :-)

提交回复
热议问题