我有一个长期运行的过程,我想在主应用程序表单上显示一个表单,解释该表单可以在无处不在的圆圈进度条上运行很长时间。我什么都无法正常工作。表单显示不正确或没有为进度圈设置动画。如果我尝试使用如图所示的其他方法,则该任务无法完成!
private void lbMethods_SelectedIndexChanged(object sender, EventArgs e)
{
switch (lbMethods.SelectedIndex)
{
case (int)Methods.none:
break;
case (int)Methods.Susan:
Log("Starting Susan Edge Detection");
Progressing("Please wait for edge detection");
Task t = new Task(() => ProcessSusan());
while (!t.IsCompleted)
{
Application.DoEvents();
}
Log("Detection Finished");
Progressing("", false);
break;
default:
break;
}
}
private void ProcessSusan()
{
Susan s = new Susan(CurrentImage);
List<IntPoint> corners = s.GetCorners();
}
private void Progressing(string message, bool Show = true)
{
if (Show)
{
lblStatus.Text = message;
Progress.Style = ProgressBarStyle.Continuous;
}
else
{
lblStatus.Text = "...";
Progress.Style = ProgressBarStyle.Blocks;
}
}
长期运行的表单代码如下所示:
public partial class FrmProcessing : Form
{
public string description { get; set; }
public FrmProcessing(string description)
{
InitializeComponent();
lblDescription.Text = description;
}
// Let the calling method close this form.
public void Close()
{
this.Close();
}
}
最佳答案
Application.DoEvents()
通常被滥用。除了通过UI重新输入代码的常见问题之外,您还正在执行busy-waiting loop。
您没有指定要在何处显示模态对话框。据我了解,代码可能如下所示:
private void lbMethods_SelectedIndexChanged(object sender, EventArgs e)
{
switch (lbMethods.SelectedIndex)
{
case (int)Methods.none:
break;
case (int)Methods.Susan:
Log("Starting Susan Edge Detection");
Progressing("Please wait for edge detection");
var dialog = new FrmProcessing();
dialog.StartTaskFunc = () =>
Task.Run(ProcessSusan);
dialog.ShowDialog();
Log("Detection Finished");
Progressing("", false);
break;
default:
break;
}
}
public partial class FrmProcessing : Form
{
public Func<Task> StartTaskFunc { get; set; }
public string description { get; set; }
public FrmProcessing(string description)
{
InitializeComponent();
lblDescription.Text = description;
// async event handler for "Form.Load"
this.Load += async (s, e) =>
{
// start the task and await it
await StartTaskFunc();
// close the modal form when the task finished
this.Close();
};
}
}
这只是一个基本的实现。您应该为
ProcessSusan
添加一些异常处理,取消和进度报告逻辑。这是有关如何执行此操作的很好的阅读:Enabling Progress and Cancellation in Async APIs。我最近也回答了a similar question。看看是否可以使用相同的方法。
关于c# - 带有对话框的长期任务,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21068965/