WinForm如何托管一个长时间运行的IronPython脚本,并为progress change更新UI

2024-09-19 23:30:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个WinForm作为IronPython主机,在IronPython运行时,脚本可以更新UI来报告进度。我有以下代码,它确实更新了UI,但问题是窗口没有响应。谢谢你的帮助。在

namespace TryAsyncReport
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        //use python
        private async void button1_Click(object sender, EventArgs e)
        {
            IProgress<ProgressReportInfo> progress = new Progress<ProgressReportInfo>(ReportProgress);
            await Task.Run(() =>
            {
                ScriptEngine engine = Python.CreateEngine();
                ScriptScope scope = engine.CreateScope();
                string script = "for i in range(1000000):\r\n";
                script += "   progress.Report(ProgressReportInfo(i / 10000, str(i / 10000)));\r\n";
                scope.SetVariable("progress", progress);
                scope.SetVariable("ProgressReportInfo", typeof(ProgressReportInfo));
                var code = engine.CreateScriptSourceFromString(script);
                code.Execute(scope);

            });

        }

        private void ReportProgress(ProgressReportInfo info)
        {
            progressBar1.Value = info.Percentage; 
            label1.Text = info.Status; 
        }

    }

    public class ProgressReportInfo
    {
        public ProgressReportInfo(int percentage, string status)
        {
            Percentage = percentage;
            Status = status;
        }
        public int Percentage { set; get; }
        public string Status { set; get; }
    }

}

Tags: infouistringstatusscriptprivatepublicengine
1条回答
网友
1楼 · 发布于 2024-09-19 23:30:16

您必须Invoke到UI线程:

    private void ReportProgress(ProgressReportInfo info)
    {
        // or better BeginInvoke
        Invoke(() =>
        {
            progressBar1.Value = info.Percentage;
            label1.Text = info.Status;
        });
    }

而且你不需要awaitTask.Run。在

另外,考虑不要报告每一个进展变化,而是说每1000个变化。在

另一种解决方案是使用polling watcher(您的脚本更改volatile变量的值,该值在计时器中检查)

相关问题 更多 >