1 回答

TA贡献1804条经验 获得超3个赞
不同之处在于您的 goroutine 进入执行 UI 例程的队列,如文档中所述:
// 调用队列 f 在 UI go-routine 上运行,在 f 可能被调用之前返回。
UI-routine 执行一个循环,所以不能同时处理改变磁带的ProgressBar。为了得到想要的结果,需要在单独的 goroutine 中运行处理函数。修改后的代码:
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"time"
"github.com/google/gxui"
"github.com/google/gxui/drivers/gl"
"github.com/google/gxui/math"
"github.com/google/gxui/samples/flags"
)
func appMain(driver gxui.Driver) {
theme := flags.CreateTheme(driver)
layout := theme.CreateLinearLayout()
layout.SetHorizontalAlignment(gxui.AlignCenter)
progressBar := theme.CreateProgressBar()
progressBar.SetDesiredSize(math.Size{W: 480, H: 60})
progressBar.SetTarget(100)
button := theme.CreateButton()
button.SetText("Start")
t0 := time.Now()
button.OnClick(func(gxui.MouseEvent) {
go func() {
N := 100
for count := 0; count < N; count++ {
resp, err := http.Get("http://example.com")
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
driver.Call(func() {
progressBar.SetProgress(count * 100 / N)
})
fmt.Println(count)
fmt.Println(ioutil.ReadAll(resp.Body))
fmt.Printf("Elapsed time: %v\n", time.Since(t0))
}
progressBar.SetTarget(100)
}()
})
layout.AddChild(button)
layout.AddChild(progressBar)
window := theme.CreateWindow(500, 100, "Test")
window.SetScale(flags.DefaultScaleFactor)
window.AddChild(layout)
window.OnClose(driver.Terminate)
}
func main() {
gl.StartDriver(appMain)
}
- 1 回答
- 0 关注
- 154 浏览
添加回答
举报