来自Async.AwaitEvent和线程的异步

时间:2012-03-31 20:38:26

标签: multithreading f# async-await

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

我无法在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

1 个答案:

答案 0 :(得分:3)

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

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

对我来说看起来不对,因为在完成处理之后你才开始听完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,然后等待完成。