1 回答

TA貢獻1810條經驗 獲得超4個贊
返回值
你可以返回值。
func DoTimeConsumingStuff() int {
time.Sleep(1 * time.Second)
counter++
return counter
}
然后在單擊按鈕時生成一個匿名 goroutine,以免阻塞 UI。
counterButton := widget.NewButton("Increment", func() {
go func() {
counter := model.DoTimeConsumingStuff(counterChan)
UpdateCounterLabel(counter)
}()
})
打回來
您可以將該UpdateCounterLabel函數傳遞給您的模型函數,也就是回調。
func DoTimeConsumingStuff(callback func(int)) {
time.Sleep(1 * time.Second)
counter++
callback(counter)
}
counterButton := widget.NewButton("Increment", func() {
go model.DoTimeConsumingStuff(UpdateCounterLabel)
})
渠道
也許您還可以將一個通道傳遞給您的模型函數。但是使用上述方法,這似乎不是必需的。潛在地,如果你有不止一個反價值。
func DoTimeConsumingStuff(counterChan chan int) {
for i := 0; i < 10; i++ {
time.Sleep(1 * time.Second)
counter++
counterChan <- counter
}
close(counterChan)
}
然后在 GUI 中,您可以從通道接收,再次在 goroutine 中,以免阻塞 UI。
counterButton := widget.NewButton("Increment", func() {
go func() {
counterChan := make(chan int)
go model.DoTimeConsumingStuff(counterChan)
for counter := range counterChan {
UpdateCounterLabel(counter)
}
}()
})
當然,您也可以再次使用在每次迭代時調用的回調。
- 1 回答
- 0 關注
- 169 瀏覽
添加回答
舉報