我正在使用 GTK# 构建 GUI。一些数据在后台处理,我想在用户界面上查看一些有关进度的信息。这是一些代码,演示了我尝试执行此操作的方式:
using System;
using Gtk;
using System.Threading.Tasks;
using System.Threading;
public partial class MainWindow: Gtk.Window
{
//a button and a textfield
private VBox VB = new VBox();
private Button B = new Button("Push dis");
private Label L = new Label("0");
public MainWindow () : base (Gtk.WindowType.Toplevel)
{
B.Clicked += OnClickEvent;
////////////////////
VB.PackStart (B);
VB.PackStart (L);
Add (VB);
ShowAll ();
Build ();
}
protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
//async method incrementing variable, simulating some work and sending its progress
protected async Task CounterGUIUpdateAsync(IProgress<string> progress)
{
await Task.Run (() => {
for (int i = 0; i <= 10000; i++) {
Thread.Sleep (100);
if(progress != null)
{
var stri = Convert.ToString(i);
progress.Report(stri);
}
}
});
}
//event handler for the button
protected async void OnClickEvent(object sender, EventArgs e)
{
var ProgressIndicator = new Progress<string> (ReportProgress);
await CounterGUIUpdateAsync (ProgressIndicator);
}
//action connected to the progress instance
protected void ReportProgress(string value)
{
L.Text = value;
}
}
运行代码将按预期开始,但在某些时候,显示的计数器可能会卡住。 GUI 将不再更新,如果已最小化,则变为黑色。但它仍然有效。
非常感谢您的帮助。
我认为你的问题是你在使用 Gtk+ API 时没有使用主线程(gui 线程)。您需要使用 Gtk.Application.Invoke() 传递操作 UI 的委托,以便在正确的线程中执行操作。
您可以阅读更多相关内容here http://www.mono-project.com/Responsive_Applications#Gtk.Application.Invoke.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)