0

I have a class written in C#. In it I want to run a certain function in parallel on a list. After it completes on each item I would like to update a progress bar. However, I get very odd behavior from my program. It executes the event and reaches my sub but never proceeds to actually execute any code. Instead it just freezes. (I've mixed vb.net and c#. It will be rewritten at some point)

so in my windows form I call

    progressBar.Visible = True
    progressBar.Value = 0
    progressBar.Maximum = dataGrid.SelectedRows.Count

    AddHandler quoteManager.refreshStarted, AddressOf progressBarCounter
    quoteManager.refreshAllAsync(list)

and the event is simply

Private Sub progressBarCounter()
    Me.Invoke(Sub()
                  If progressBar.Value = progressBar.Maximum Then
                      progressBar.Visible = False
                  Else
                      progressBar.Value += 1
                  End If
              End Sub)
End Sub

and in the quote manager class I have this defined.

    public event Action refreshStarted;

    public void refreshAllAsync(List<BindableQuote> bindableQuotes)
    {
        bindableQuotes.AsParallel()
            .WithDegreeOfParallelism(10)
            .ForAll((quote) => {
                quote.refreshAll();
                if (refreshStarted != null) { refreshStarted(); }
            });
    }

So for some reason I get it to enter progressBarCounter on each item in the list but it never exists. Instead it just keeps the form frozen.

Leon
  • 15
  • 2

2 Answers2

0

What appears to be happening here is that you access UI objects from multiple threads.

That's not supported. You'll have to run this code on a worker thread, and let it somehow accumulate progress, and send messages back to the UI thread. The BackgroundWorker class can help you implement the marshalling back to the UI thread.

0

I am not exactly sure this is what is happening, but it looks like progressBarCounter is blocking because you are calling Invoke. Should you be using BeginInvoke instead? Using BeginInvoke might solve the deadlock issue. See this post: What's the difference between Invoke() and BeginInvoke()

Community
  • 1
  • 1
YWE
  • 2,849
  • 28
  • 42
  • yes that works!!! However, shouldn't setting up a lock around this section work as well? But it doesn't seem to for some reason – Leon Nov 26 '10 at 20:33
  • also it seems that my form doesn't freeze but the progress bar doesn't show anything until the end when it disappears. – Leon Nov 26 '10 at 20:42