【发布时间】:2016-06-08 10:17:45
【问题描述】:
当我点击一个按钮时,我的 winform 中有一个冗长的处理;即,我正在加载大量文件并处理它们。在处理期间,我的 GUI 冻结且无响应,这是一个问题,因为处理可能需要 10 分钟以上。有没有办法将代码放入某种气泡或其他东西中,以便我可以在处理文件时使用 GUI?甚至可以添加“取消”按钮。
编辑:René 的解决方案有效,这也是我想要的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++;
}
}
【问题讨论】:
-
看看async / await msdn.microsoft.com/en-us/library/mt674882.aspx
-
你可以使用BackgroundWorker。请参阅此链接 - msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx 对于取消按钮操作,请使用 CancelAsync 方法。
-
是的,有不同的方法可以实现这一点。您可能应该搜索 async-await(如果您使用的是 net fw 4.5 或更高版本),因为您已经正确标记了它,然后尝试尝试;)
标签: c# winforms async-await