在异步读取流的同时将事件提升到主线程

时间:2013-12-05 21:59:50

标签: multithreading events asynchronous f#

我正在尝试将传感器的输出作为无限流提取,而不会阻止主应用程序。读取循环的每次迭代都必须通过包含我刚读过的字节数组的事件通知主线程。我需要启动和停止生成此事件流的方法。事件提升应该像MouseMove事件一样,所以我可以轻松地听取它们并从Event模块中进行所有聚合。我已经尝试过async {}和线程以及背景工作者。

传感器的行为非常类似于/ dev / urandom linux文件,除了内部结构

type SensorReader() = 
    let progress = new Event<_>();

    member this.BeginRead () =
        let sr = new IO.StreamReader("/dev/urandom") 
        let charBuffer = Array.zeroCreate<byte> 16
        let rec loop () = async {
        //read next 16-byte chunk and trigger event to the main Thread
            return! loop() }
        Async.Start(loop())

    member this.ProgressChanged = progress.Publish

或类似

type SensorReader() =
    let progress = new Event<_>()


    let worker = new BackgroundWorker(WorkerReportsProgress = true, 
                                      WorkerSupportsCancellation = true)

    let sr = new IO.StreamReader("/dev/urandom") 
    let charBuffer = Array.zeroCreate<char> 16

    do worker.DoWork.Add(fun args ->

        let rec iterate() =
            if worker.CancellationPending then
                args.Cancel <- true
            //else read next chunk and report event

    iterate())

//do worker.ProgressChanged.Add(fun args ->
//    progressChanged.Trigger(*our new data from sensor*)

member this.ProgressChanged = progressChanged.Publish

member this.BeginReadAsync() = worker.RunWorkerAsync()
member this.EndReadAsync() = worker.CancelAsync()

希望你们帮助我,谢谢

0 个答案:

没有答案