lxn / walk

A Windows GUI toolkit for the Go Programming Language
Other
6.8k stars 885 forks source link

add item to listBox from thread #674

Open Hanson opened 4 years ago

Hanson commented 4 years ago

when I start the exe , I will create a tcp client to dial server every 3 seconds and I want to record the response to the listBox.

But It will exit with error that I don't know what it is.

func main() {
// conn create
        mw := &MyMainWindow{}

    go listen(conn, mw)
// MainWindow run here
}

func listen(conn net.Conn, mw *MyMainWindow)  {
    for {
                fmt.Fprintf(conn, "{\"data\":\"check\"}\r\n")
        message, _ := bufio.NewReader(conn).ReadString('\n')
        item := EnvItem{message: message}

                // when I add this , It will crash
        mw.model.items = append(mw.model.items, item)

        time.Sleep(3 * time.Second)
    }
}
jscholes commented 4 years ago

You can't carry out GUI-related actions from another thread or goroutine. You should use the synchronization functions provided by Walk to run a function on the GUI thread.

StephanVerbeeck commented 4 years ago

and this is an example of how you do that. The variable mainWindow might have a different name in your program currently!

        mainWindow.Synchronize(func() {
            put code to update screen here
        })