当我点击一个按钮时,我在我的winform中进行了长时间的处理;即,我正在加载大量文件并处理它们。在处理期间,我的GUI被冻结并且没有响应,这是一个问题,因为处理可能需要10分钟以上。有没有办法将代码放入某种泡泡或某种东西中,以便在处理文件时使用GUI?也许甚至添加“取消”按钮。在处理过程中启用响应式图形用户界面
编辑:勒内的解决方案有效,而且,这里的progressbar
控制我也想:
private async void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = ValueWithTOtalNumberOfIterations.Length;
IProgress<int> progress = new Progress<int>(value => { progressBar1.Value = value;});
await Task.Run(() =>
{
var tempCount = 0;
//long processing here
//after each iteration:
if (progress != null)
{
progress.Report((tempCount));
}
tempCount++;
}
}
看异步/等待https://msdn.microsoft.com/en-us/library/mt674882.aspx –
可以使用的BackgroundWorker。请参阅此链接 - https://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx对于取消按钮操作,请使用CancelAsync方法。 – Sanket
是的,有不同的方法来实现这一点。您应该搜索async-await(如果您使用net fw 4.5或更高版本),因为您已经正确标记了该内容,然后提出您的尝试;) – Mono