【问题标题】:Async from Async.AwaitEvent and threading来自 Async.AwaitEvent 和线程的异步
【发布时间】:2012-04-01 17:31:33
【问题描述】:

这是我处理的问题的简化版本。 它有一个我无法控制的线程循环。 我处理消息的时间超过了循环抛出的时间。

除了 StartAsync 中的标记部分之外,我无法重写 mytype 中的任何内容。

您能否指导我了解可以处理此类情况的说明? 例如,是否有带有队列的 syncContext.Post 版本? 任何帮助表示赞赏

type mytype () = 
  let FinishedEvt    = new Event<_>()
  let FirstEvt       = new Event<_>()
  member x.First       = FirstEvt.Publish
  member x.Finished    = FinishedEvt.Publish

  member x.StartAsync() = 

     async {
     let syncContext =  match System.Threading.SynchronizationContext.Current with
                        | null -> new System.Threading.SynchronizationContext()
                        | other -> other 
     do! Async.SwitchToNewThread()
     //**the code that I can change is here**
     Thread.Sleep(100)
     syncContext.Post(SendOrPostCallback(fun _ -> FirstEvt.Trigger    ()), null)
     Thread.Sleep(200)
     syncContext.Post(SendOrPostCallback(fun _ -> FinishedEvt.Trigger ()), null)
     do! Async.SwitchToContext(syncContext) 
     ()
  }
     let hopingobject = mytype()
     let wf1 = lock readLock1 
                    (fun () -> 
                               async{ printfn "watching"
                                      do! Async.AwaitEvent hopingobject.First
                                      printfn "first event received"
                                      do! Async.AwaitEvent hopingobject.Finished
                                      printfn "I never get called"} )

     hopingobject.StartAsync() |> Async.Start
     wf1 |> Async.RunSynchronously
     printfn "the end"
     Console.ReadKey() |> ignore

【问题讨论】:

    标签: multithreading f# async-await


    【解决方案1】:

    我不清楚你要做什么,哪些部分是必不可少的,但这一点

    async{ printfn "watching" 
           do! Async.AwaitEvent hopingobject.First 
           printfn "first event received" 
           do! Async.AwaitEvent hopingobject.Finished 
           printfn "I never get called"}
    

    在我看来是错误的,因为您在处理完 First 之后才开始收听 Finished,此时 Finished 可能已经被解雇了。也许你想要更像

    async{ printfn "watching" 
           let! a = Async.AwaitEvent hopingobject.First |> Async.StartChild
           let! b = Async.AwaitEvent hopingobject.Finished |> Async.StartChild
           do! a
           printfn "first event received" 
           do! b
           printfn "hurray, I never called"}
    

    (我是在浏览器中写代码,希望是对的。)思路是,从一开始就开始监听,然后等待First,然后等待Finished。

    【讨论】:

    • 确实如此。我可能可以这样处理这个问题。 async continuation 与 Async 模块的线程函数的组合非常强大。
    • 有了这个结构,我可以先做一些繁重的处理! b,不要错过完成的事件,因为它的完成(也就是事件触发)将在 b 中被记住。
    • 实际上,我同时意识到我需要观察许多连锁事件。我本可以使用 AsyncObservable,但链接的数量是不确定的。所以我选择了一个带有多线程同步的邮箱处理器。我不会推荐它来度蜜月。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-26
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多