使用调度程序更新WPF进度条

ali*_*ce7 4 c# wpf multithreading progress-bar

我正在尝试使用调度程序更新进度条但不知何故无法考虑将dispatcher.Invoke放在哪里以及在其中传递的内容.

我试图导入文件,需要向用户显示使用进度条导入的文件数量.

所以我有一个代表:

public delegate void DelegateA(ProgressClass progressClass);
Run Code Online (Sandbox Code Playgroud)

即调用委托并传递函数进行调用.

DelegateA(FunctionA);
Run Code Online (Sandbox Code Playgroud)

因此,在导入每个文件时,它会调用FunctionA.

private void FunctionA(ProgressClass progressClass)
{
    **//Put dispatcher.invoke here?**
    progressbar.updateprogress(progressclass);
    progressbar.show();
}
Run Code Online (Sandbox Code Playgroud)

progressclass有两个属性,用于设置进度条的值(已处理的数量)和要处理的项目总数.

我无法理解在InvokeMethod中传递的委托方法(THreadPriority,委托方法)?

对不起,如果有什么不清楚的话.

Har*_*san 7

如果您尝试从某些非UI线程更新UI,则可以执行以下操作:

//here progress bar is a UIElement
progressBar.Dispatcher.BeginInvoke(
           System.Windows.Threading.DispatcherPriority.Normal
           , new DispatcherOperationCallback(delegate
                   {
                       progressBar1.Value = progressBar1.Value + 1;
                       //do what you need to do on UI Thread
                       return null;
                   }), null);
Run Code Online (Sandbox Code Playgroud)

此代码取自关于从后台线程更新UI 的好帖子


Ed *_*tes 2

我假设您已经启动了后台线程来导入文件。为此,您应该考虑使用BackgroundWorker,它是轻量级的,并且内置了一个使用事件报告进度的机制(例如,ProgressBar)。

如果您想在正在执行的处理中的任何位置使用新线程,只需声明一个委托,向目标添加一个函数,然后调用 Dispatcher.BeginInvoke:

Dispatcher.BeginInvoke(DispatcherPriority.Normal, new UpdateProgressDelegate(UpdateProgress), myProgressData);

//...

private delegate void UpdateProgressDelegate(ProgressClass progressClass);

void UpdateProgress(ProgressClass progressClass)
{
    progressbar.updateprogress(progressclass);
    progressbar.show(); 
}
Run Code Online (Sandbox Code Playgroud)