繁体   English   中英

F#STA线程异步

[英]F# STA Thread Async

我从GUI线程中调用了这个函数:

let updateImageLoop (pprocess : PlotProcess) (target : IUpdatableImageView<'T>) =
    async {
      while target.Continue do
        let context = System.Threading.SynchronizationContext.Current
        do! Async.SwitchToThreadPool()
        System.Threading.Thread.Sleep(10000)
        do! Async.SwitchToContext(context)
        let image = target.CreateImage()
        match image with
        | Some userImage -> do! target.UpdateImageView userImage 
        | None -> ()
    } |> Async.StartImmediate

执行方法target.UpdateImageView时会出现问题,生成异常:

调用线程必须是STA,因为许多UI组件都需要这个。

我知道,但这就是我所做的

do! Async.SwitchToContext(context)

消除函数SwitchToContext和SwitchToThreadPool,删除异常,但GUI只是冻结。 这是有道理的,但为什么我不能在线程之间切换?

生成问题的函数是UpdateImageView。 我测试它有没有让它异步。

member this.UpdateImageView  etoimage =
  async {
    let imageview = new Eto.Forms.ImageView()
    imageview.Image <- etoimage
    this.Content <- imageview
  }

编辑---

Testing with this code:
let updateImageLoop (pprocess : PlotProcess) (target : IUpdatableImageView<'T>) =
    let context = System.Threading.SynchronizationContext.Current
    let printThread text =
        printfn "[%d] %s" System.Threading.Thread.CurrentThread.ManagedThreadId text
    async {
      while target.Continue do
        printThread "begining"
        do! Async.SwitchToThreadPool()
        printThread "after swith to thread pool"
        let image = target.CreateImage()
        match image with
        | Some userImage -> 
            printThread "before switch to context"
            do! Async.SwitchToContext context 
            printThread "after switch to context"
            target.UpdateImageView userImage 
        | None -> ()
    } |> Async.StartImmediate

印刷品:

[1] begining 
[4] after swith to thread pool 
[4] before switch to context 
[5] after switch to context
  1. 使用[<STAThread>]

  2. 使用guiContext处理GUI

在GUI创建(框架初始化)中记住guiContext

let guiContext = System.Threading.SynchronizationContext.Current 

并将其传递给异步GUI执行

// the async GUI execute 
async {
            let currentContext = System.Threading.SynchronizationContext.Current 
            do! Async.SwitchToContext(guiContext)
            f() // work on the GUI
            do! Async.SwitchToContext(currentContext)   
}

把等待放在一个额外的步骤,以保持其可组合。

暂无
暂无

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

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