c# - Background worker - report progress with string array -


I need to back multiple STRING values ​​in each background in each loop, so I used ReportProgress II parameter as string array Tried to use Example of code:

  Private zero background worker 1_DoWork (Object Sender, DoWorkEventArgs e) {string [] workerResult = new string [2]; (Int i = 0; i & lt; someNumber; i ++) {// Some heavy calculation workers [0] = [0] = "this string"; Worker [1] = "some other string"; Background Worker 1 Work progress (i, work result) // Also the workers who attempted [] and [2]}} Private Zero background worker 1 progress change (object sender, progress change event ARG E) {string [] results = (string [] ) E.UserState; MessageBox.Show (Results [0]); // line of error. MessageBox.Show (Results [1]); // line of error}   

It compiles, but at runtime, I try to reach the user's returned string, I get an error: "Not an instance of the object reference object It is set for me.

It seems to me that there is something wrong when passing the array parameter to the progressing delegates, or the method in progress when trying to set the result array values.

Your code snippet is unable to recreate the problem. A standard error is to call ReportProgress and then continue to modify the object. Run the event handler It takes some time to look at the modified object, not the original. You avoid making it a new object so that the event handler can always work with the original. In this way:

  // Some heavy calculations (int i = 0; i & lt; 2; ++ i) {string [] workerResult = ne W string [2]; worker [0] = "this string"; worker [1] = "some other string"; background report 1. Report progress (i, worker result); }   

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

Comments