wxhaskell异步更新 [英] wxhaskell asynchronous updates

查看:126
本文介绍了wxhaskell异步更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用WxHaskell以图形方式显示使用TCP(我使用Data.Binary解码)通告状态更新的程序的状态。收到更新时,我想更新显示。所以我希望GUI以异步方式更新它的显示。我知道 processExecAsync 异步运行命令行进程,但我不认为这是我想要的。

I am using WxHaskell to graphically show the state of a program that advertises state updates using TCP (which I decode using Data.Binary). When an update is received, I want to update the display. So I want the GUI to update its display asynchronously. I know that processExecAsync runs a command line process asynchronously, but I don't think this is what I want.

推荐答案

这是使用事务变量(即软件事务内存)的粗略代码。您可以使用IORef,MVar或其他许多构造。

This is rough code using transactional variables (i.e. software transactional memory). You could use an IORef, MVar, or numerous other constructs.

main = do
    recvFunc <- initNetwork
    cntTV <- newTVarIO 0
    forkIO $ threadA recvFunc cntTV
    runGUI cntTV 0

上面你启动程序,初始化网络和一个共享变量 cntTV

Above you start the program, initialize the network and a shared variable cntTV

threadA recvCntFromNetwork cntTVar = forever $ do
    cnt <- recvCntFromNetwork
    atomically (writeTVar cntTVar cnt)

threadA 从网络接收数据并将计数器的新值写入共享变量。

threadA receives data from the network and writes the new value of the counter to the shared variable.

runGUI cntTVar currentCnt = do
    counter <- initGUI
    cnt <- atomically $ do
        cnt <- readTVar cntTVar
        if (cnt == currentCnt)
            then retry
            else return cnt
    updateGUICounter counter cnt
    runGUI cntTVar cnt

runGUI 读取共享变量,如果有更改会更新GUI计数器。仅供参考,runGUI线程不会在 retry 上被唤醒,直到 cntTVar 被修改,所以这不是CPU hogging polling loop。

runGUI reads the shared variable and if there is a change will update the GUI counter. FYI, the runGUI thread won't wake up on retry until cntTVar is modified, so this isn't a CPU hogging polling loop.

在这段代码中,我假设你有一个名为 updateGUICounter initGUI initNetwork 。我建议你使用Hoogle来查找你还不知道的其他功能的位置,并学习一些关于每个模块的知识。

In this code I've assumed you have functions named updateGUICounter, initGUI, and initNetwork. I advise you use Hoogle to find the location of any other functions you don't already know and learn a little about each module.

这篇关于wxhaskell异步更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆