【发布时间】: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