后台工作 - 举报字符串数组进展数组、字符串、后台、进展

2023-09-04 00:07:29 作者:装聋装瞎装哑巴

我需要从我的每个循环BackgroundWorker的返回多个字符串值,所以我试图用ReportProgress第二个参数字符串数组。的code例:

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:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    string[] workerResult = new string[2];
    for (int i=0; i<someNumber; i++)
    {
        //do some heavy calculating
        workerResult[0] = "this string";
        workerResult[1] = "some other string";
        backgroundWorker1.ReportProgress(i, workerResult) // also tried workerResult[] and [2]
    }
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    string[] results = (string[])e.UserState;

    MessageBox.Show(results[0]); // line of error
    MessageBox.Show(results[1]); // line of error
}

它编译,但在运行时,在那一刻我尝试访问Userstate返回的字符串,我得到一个错误:未设置为一个对象的实例对象引用

It compiles, but on runtime in the moment I try to access Userstate returned string, I get an error: "Object reference not set to an instance of an object."

对于我来说,似乎LIK试图设置结果数组值时传递数组参数ProgressChanged委托,或在ProgressChanged方法时,什么是错的。

For me it seems lik something is wrong when passing array parameter to ProgressChanged delegate, or in ProgressChanged method when trying to set results array values.

推荐答案

您code段是不能复制的问题。一个标准的错误是调用ReportProgress(),然后继续修改对象。这需要一段时间的事件处理程序运行时,它会看到修改的对象,而不是原来的。您只需创建一个新的对象,这样的事件处理程序总是与原创作品避免这种情况。像这样的:

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.