Z
Z
Zulkund2016-09-27 18:13:21
C++ / C#
Zulkund, 2016-09-27 18:13:21

How to update ProgressBar in c# side thread?

Sorry, the topic is beaten, but I do not understand what needs to be done.
I start the thread:

private void button3_Click(object sender, EventArgs e)
        {
                ProgressBar.Maximum = listToCalc.Count;
                ProgressBar.Value = 0;
                ProgressBar.Step = 1;
                listOfWells.Clear();
                thread = new Thread(calc);
                thread.Start();
            }

And an error occurs!
public void calc()
        {
            for (int i = 0; i < listToCalc.Count; i++) {
                listOfWells.Add(new Well(listToCalc[i]));
                listOfWells[i].calcP();
                ProgressBar.PerformStep();  - Выскакивает исключение!
            }
        }

Please fix it in a working version. Any delegates and dispatchers simply cannot understand. Thanks in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rou1997, 2016-09-27
@Zulkund

this.Invoke((MethodInvoker) delegate() {
     ProgressBar.PerformStep();
});

It is very easy to understand, a delegate is a function, therefore, with round and curly braces, the difference from a normal function is that it is used as a variable (method parameter), it is passed to the method this.Invoke(remember this) to be called on the UI thread, and MethodInvoker is simply type casting.
Another option:
this.Invoke((MethodInvoker) (() =>
{
    ProgressBar.PerformStep();
}));

Basically, this is the code:
this.Invoke((MethodInvoker) () =>
{
    ProgressBar.PerformStep();
});

Where the variable value (same as 0.5, "abc"or new Button()) is the following:
() =>
{
    ProgressBar.PerformStep();
}

The rest is the usual cast to MethodInvoker, why then these brackets around the value, we don’t write int x = (int)(0.5);, alas, when casting types, it’s not always possible to limit yourself to parentheses only for the type and omit them for the value being cast, of course you can forget about this and it won’t compile, but with experience you already know, if the cast does not compile, then you need to try adding parentheses for the value.

A
AxisPod, 2016-09-28
@AxisPod

Use https://msdn.microsoft.com/ru-ru/library/system.wi...
Because you cannot update from another UI thread and MS has made a ready-made tool for this. And bikes are not required in this case.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question