non*_*ion 17 c# wpf wpf-controls
我在进度条实时显示更新时遇到了一些麻烦.
这是我现在的代码
for (int i = 0; i < 100; i++)
{
progressbar1.Value = i;
Thread.Sleep(100);
}
Run Code Online (Sandbox Code Playgroud)
但由于某种原因,进度条在函数运行时显示为空,然后在函数完成运行之前没有任何内容.有人可以向我解释如何做到这一点?我是C#/ WPF的新手,所以我不能100%确定如何在不同的线程上实现Dispatcher(如其他一些帖子所示)来解决这个问题.
为了澄清,我的程序有一个按钮,按下时,从文本框中获取值,并使用API检索信息,并根据它创建标签.我希望在每行数据处理完毕后更新进度条.
这就是我现在所拥有的:
private async void search(object sender, RoutedEventArgs e)
{
var progress = new Progress<int>(value => progressbar1.Value = value);
await Task.Run(() =>
{
this.Dispatcher.Invoke((Action)(() =>
{
some pre-processing before the actual for loop occur
for (int i = 0; i < numberofRows; i++)
{
label creation + adding
((IProgress<int>)progress).Report(i);
}
}));
});
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
Ale*_*bin 27
如果您使用的是.NET 4.5或更高版本,则可以使用async/await:
var progress = new Progress<int>(value => progressBar.Value = value);
await Task.Run(() =>
{
for (int i = 0; i < 100; i++)
{
((IProgress<int>)progress).Report(i);
Thread.Sleep(100);
}
});
Run Code Online (Sandbox Code Playgroud)
您需要使用async关键字标记您的方法才能使用await,例如:
private async void Button_Click(object sender, RoutedEventArgs e)
Run Code Online (Sandbox Code Playgroud)
non*_*ion 23
管理使其工作.我所需要做的就是取而代之的是做到这一点
progressBar1.value = i;
Run Code Online (Sandbox Code Playgroud)
我只是必须这样做
progressbar1.Dispatcher.Invoke(() => progressbar1.Value = i, DispatcherPriority.Background);
Run Code Online (Sandbox Code Playgroud)
您应该使用.NET中包含的BackgroundWorker,它为您提供了报告事件中后台线程进度的方法.创建BackGroundWorker的线程会自动调用此事件.
的BackgroundWorker.ProgressChanged可以被用来报告一个异步操作的给用户的进展.
// This event handler updates the progress bar.
private void backgroundWorker1_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
Run Code Online (Sandbox Code Playgroud)
有关使用此信息的详细信息,请参阅MSDN.
| 归档时间: |
|
| 查看次数: |
43222 次 |
| 最近记录: |