djskj189 djskj189 - 5 days ago 5
C# Question

Make a method report progress in Winform C#

I have two classes, form1.cs and test.cs

Form1.cs calls some public method in test.cs. Is it possible to somehow make the program report the progress?

For example,

In Form1.cs

test.CallTestMethod();


In test.cs

public void CallTestMethod()
{
// Read excel file line by line (~5000 lines)
// I used double for loops to iterate row and col
}


I know how to report progress if the method is in the form element, but how would I report progress if im calling an external method? Is it even possible?

Thanks

Answer

You're going to need CallTestMethod() to execute in a non-UI thread. give it a parameter Action<double> reportProgressPercent. Have it call reportProgressPercent as appropriate. When Form1 calls CallTestMethod(), have it pass in an appropriate lambda that invokes into the UI thread to report progress.

public void CallTestMethod(Action<double> reportProgressPcnt)
{
    foreach (var blah in whatever)
    {
        foreach (var foo in innerLoopWhatever)
        {
            //  do stuff. On every nth iteration or whatever, figure out what 
            //  your completed percentage is and pass it to reportProgressPcnt
            double progress = (curRow / totalRows) * 100;
            reportProgressPcnt(progress);
        }
    }
}

Form1.cs

progBar1.Maximum = 100;
progBar1.Step = 1;

Task.Run(() => {
    test.CallTestMethod(pcnt => {
        Invoke(new Action(() => progBar1.Value = (int)pcnt));
    })
});

If you want to report progress in some other way, change the parameters to your Action; for example:

public void CallTestMethod(Action<int, int> reportCurrentRowAndColumn)
{
    int curRow = 0;
    int curCol = 0;

    //...blah blah loop stuff, update values of curRow & curCol as needed...
            reportCurrentRowAndColumn(curRow, curCol);

Then maybe your Action could update a pair of labels displaying current row and current column.

Comments