GTK GUI因异步/等待而冻结,并且进度T冻结. [英] GTK GUI freezes with async/await and Progress<T>

查看:77
本文介绍了GTK GUI因异步/等待而冻结,并且进度T冻结.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用GTK#来构建GUI.一些数据在后台处理,我想在用户界面上查看一些有关进度的信息.这是一些代码,展示了我尝试执行此操作的方式:

I'm using GTK# to build a GUI. Some data is processed in the background and I'd like to see some info about the progress on the user interface. Here is some code demonstrating the way I am trying to do this:

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将不再更新,如果已将其最小化,则将变黑.它仍然可以运行.

Running the code will start off as expected, but at some point it is likely that the displayed counter gets stuck. The GUI won't update anymore, turning black if it has been minimized. It is still functional though.

非常感谢您的帮助.

推荐答案

我认为您的问题是使用Gtk + API时没有使用主线程(gui线程).您需要使用Gtk.Application.Invoke()传递用于操纵UI的委托,以便在正确的线程中执行操作.

I think your problem is that you're not using the main thread (the gui thread) when using the Gtk+ API. You need to use Gtk.Application.Invoke() passing a delegate that manipulates the UI, so the action is performed in the correct thread.

您可以在此处了解更多信息.

You can read more about this here.

这篇关于GTK GUI因异步/等待而冻结,并且进度T冻结.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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