简体   繁体   English

从调用的操作更新WPF ProgressBar

[英]Update WPF ProgressBar from invoked action

First, I should mention that I have already read this post and this and this , but none of them seem to fix my problem. 首先,我要指出,我已经阅读这篇文章这个这个 ,但他们都不来解决我的问题。

Simply explained, I have an unmanaged DLL which is called several times inside an invoked action, ie 简单地讲,我有一个非托管的DLL,它在一个被调用的动作中被多次调用,即

var d = new List<string>();
var myData = new StringBuilder();

this.Dispatcher.Invoke(new Action(() =>
{
    myDLL.GetDataFromIndex(2, myData);
    d.Add(myData.ToString());

    myDLL.GetDataFromIndex(3, myData);
    d.Add(myData.ToString());

    myDLL.GetDataFromIndex(4, myData);
    d.Add(myData.ToString());

    //....
}
    ), System.Windows.Threading.DispatcherPriority.ContextIdle);

I want to show the progress of getting data by a ProgressBar . 我想展示通过ProgressBar获取数据的ProgressBar First, I tried to update the ProgressBar right after each DLL call by putting the following line after each d.Add(...) 首先,我尝试在每个DLL调用之后立即通过在每个d.Add(...)之后放置以下行来更新ProgressBar d.Add(...)

pbStatus.Value = newValue;

It obviously didn't work and it also ruined myDLL calls. 它显然没有用,并且还破坏了myDLL调用。 Then I learned that the ProgressBar must be updated through a BackgroundWorker , but I wasn't able to define a new BackgroundWorker inside the invoked action. 然后,我了解到必须通过BackgroundWorker更新ProgressBar ,但是我无法在调用的动作中定义新的BackgroundWorker Furthermore, the DLL calls take different times. 此外,DLL调用花费不同的时间。 For example, after GetDataFromIndex(2, ...) 20% of the process is completed, while the next indexes take 5 to 10 percent each. 例如,在完成GetDataFromIndex(2, ...) ,将完成20%的过程,而下一个索引将分别占用5%到10%。 Now I have no idea how to update the ProgressBar right after each DLL call. 现在我不知道如何在每个DLL调用之后立即更新ProgressBar Any hints or workarounds would be much appreciated due to my exhaustion from hours of pointless googling. 由于我在数小时的毫无意义的谷歌搜索中精疲力尽,因此任何提示或解决方法将不胜感激。

The dispatcher actions are beeing executed in the UI thread. 调度程序动作在UI线程中执行。 So your code design is bad at that point allready that you are doing some external call there. 因此,此时您已经在进行一些外部调用,因此您的代码设计很糟糕。 Move your PINVOKING to a background task / thread, and call dispatcher.invoke just to set the progressbar progress from the background thread. 将PINVOKING移至后台任务/线程,然后调用dispatcher.invoke,仅从后台线程设置进度条进度。

As I promised, I created this github repository to demonstrate how to work with progressbar & background task ... it is WPF and I tried to follow the MVVM pattern. 正如我所承诺的,我创建了这个github存储库来演示如何使用Progressbar和后台任务……这是WPF,我尝试遵循MVVM模式。

https://github.com/michalhainc/ProgressBarMVVMDemo https://github.com/michalhainc/ProgressBarMVVMDemo

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM