0

我对 C# 和所有线程的东西都很陌生,目前我收到“跨线程操作无效错误”。

以下是代码的相关部分:

    private LinkedList<string> _statusList = new LinkedList<string>();

    private void ReportToStatus(string message)
    {
        _statusList.AddLast(message);\
        // textStatus is a textbox.
        // And this is the exact line that is giving the error:
        textStatus.Lines = _statusList.ToArray();
    }

    private void RunTest()
    {
        // ...

        // Run the test in the background worker.
        bgwTest.RunWorkerAsync(testCase);
    }

    private void bgwTest_DoWork(object sender, DoWorkEventArgs e)
    {
        TestCase testCase = e.Argument as TestCase;

        // ...

        // Run the test.
        switch (testCase.TestType)
        {
            case "TestA":    TestA(testCase);
                             break;
        }

        e.Result = testCase;
    }

    private void TestA(TestCase testCase)
    {
        // ...

            PrintStatistic(statisticsForCoil, testCase.OutputFile);
        }
    }

    private void PrintStatistic(int[] statistics, string outputFile)
    {
        // ...

        ReportToStatus(result);
    }

我应该如何进行?

4

3 回答 3

1

_statusList 中似乎有问题。您不能从不同的线程写入它,只能读取。

来自MSDN

“LinkedList 类不支持链接、拆分、循环或其他可能使列表处于不一致状态的功能。列表在单个线程上保持一致。LinkedList 支持的唯一多线程场景是多线程读取操作。”

此外,您无法从后台线程访问 UI。您需要使用调度程序来调用 UI 线程上的操作。为此,您的代码需要如下所示

WPF

    Application.Current.Dispatcher.Invoke(new Action(delegate
                                   {
                                        textStatus.Lines = _statusList.ToArray();
                                   }));

WinForms

    textStatus.Invoke(new Action(delegate
                                   {
                                        textStatus.Lines = _statusList.ToArray();
                                   }));
于 2012-08-20T03:00:06.527 回答
1

有一个更新 UI的BackgroundWorker专用机制: BackgroundWorker.ReportProgress。例如,在您的代码中,它可能如下所示:

private void ReportToStatus(string message)
{
    _statusList.AddLast(message);
    // textStatus is a textbox.
    // And this is the exact line that is giving the error:
    bgwTest.ReportProgress(0, _statusList.ToArray());
}

//Assuming this is the method handling bgwTest's ProgressChanged event
private void bgwTest_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
     textStatus.Lines = (string[])(e.UserState);
}
于 2012-08-20T14:32:56.117 回答
0

您正在尝试从您的后台工作人员更新 UI,这将导致该异常。您可以使用 Dispatcher 来安排更新 - 或者更理想的是使用后台工作人员仅执行“后台”工作,然后在RunWorkerCompleted引发事件时执行 UI 更新。

于 2012-08-20T02:52:58.287 回答