0

I have a method that reads from database and return result items one by one using yield return. I call it in foreach loop and at each iteration it invokes to STA thread for update ProgressBar. In this case I get about 6 seconds for all for some params. But if I remove Invoke, then I get 28 seconds for the same params. I test this behavior in separate application and can say that with Invoke each iterations to main thread processing in 10 times slower. However, Invoke is allmost at 6 times faster (not slower!) in my application than in other completed examples.

Any suggestions?

In general it looks like this:

Thread thread = new Thread(() =>
{
    int itemNumber = 0;
    foreach (object item in SelectItems())
    {
        itemNumber++;

        // doing some staff ...

        Application.Current.Dispatcher.Invoke(
            new Action(() =>
            {
                ProgressBar1.Value = itemNumber * 100 / count;
            }),
            null);
    }
});
thread.IsBackground = true;
thread.Start();

Update

I think I need to say that is big application and there is about half hundred background threads. And I don't think they all can work at same time.

  • Can you add the code you have used so far? It might clarify your question. – Starceaker Dec 28 '15 at 11:57
  • I may have read it wrong but you seem to say that using Invoke makes each iteration 10 times slower but at the same time you say that removing Invoke makes your application 6 times slower. I don't really get it. Or maybe it's because of a try-catch in your loop that would catch an Exception when you try to use UI elements in a thread that's not the Dispatcher, it would effectively take some time to handle those exceptions. – nkoniishvt Dec 28 '15 at 12:13
  • I'm updated question. Please pay attention at words marked bold. Thanks. –  Dec 28 '15 at 12:19
  • No, there is no any exceptions. But when I'm checked it just now it works very fast without invoke... so, now it works, but I don't understand why... –  Dec 28 '15 at 12:28
  • As stated in the answer here: http://stackoverflow.com/questions/590590/making-sure-onpropertychanged-is-called-on-ui-thread-in-mvvm-wpf-app , WPF marshalls property changes to the UI thread automatically, so you don't need the invoke call. – o_weisman Dec 28 '15 at 12:35
  • Do NOT update your progressbar on every single item, but batch them in groups of e.g. 100 or even 1000. You're basicly killing it yourself. – Bart Dec 28 '15 at 13:16
  • I know that it's bad, but question is why code Without Invoke is much slower than with it? –  Dec 28 '15 at 13:52

0 Answers0