我需要一个 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; }
}
}