Background worker - report progress with string array

后端 未结 3 1223
终归单人心
终归单人心 2020-12-16 20:16

I need to return multiple STRING values from my backgroundworker in each loop, so I tried to use ReportProgress second parameter as string array. Example of code:

         


        
3条回答
  •  星月不相逢
    2020-12-16 20:46

    Your code snippet is incapable of reproducing the problem. A standard mistake is to call ReportProgress() and then to continue modifying the object. It takes a while for the event handler to run, it will see the modified object, not the original. You avoid this by simply creating a new object so that the event handler always works with the original. Like this:

            //do some heavy calculating
            for (int i = 0; i < 2; ++i) {
                string[] workerResult = new string[2];
                workerResult[0] = "this string";
                workerResult[1] = "some other string";
                backgroundWorker1.ReportProgress(i, workerResult);
            }
    

    Note how the array creation statement is moved inside the loop.

提交回复
热议问题