Я получаю сообщение об ошибке: «Вызывающий поток не может получить доступ к этому объекту, поскольку объект принадлежит другому поток", когда из потока WPF я пытаюсь получить доступ к объектам в массиве, созданном в рабочем потоке (который больше не активен).
Мой первый вопрос был закрыт как дубликат , но другой похожий вопрос касался доступа к элементам пользовательского интерфейса из рабочего потока, а это не то, что я хочу делать.
Вот упрощенный пример кода:
Код: Выделить всё
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void MenuItem_Click(object sender, RoutedEventArgs e)
{
ReadDoc();
}
void ReadDoc()
{
// Create the array of Paragraph that will contain all the formatted data.
// This array can be huge.
Paragraph[] doc = new Paragraph[1];
// Read all the data and fill the array using another thread to keep the UI responsive
Thread reader = new Thread(() => ReadData(doc));
reader.Start();
// Kludge (not using signals in this example)
// Make sure the fake reading thread is done before continuing
Thread.Sleep(100);
// Display some of the data
richTextBox.Document.Blocks.Add(doc[0]);
}
void ReadData(Paragraph[] doc) // This is the worker thread
{
// For this example, create a simple fake data instead of reading the file
doc[0] = new Paragraph(); // Create a new Paragraph and add a Run to it
Run run = new Run();
run.Text = "Test";
doc[0].Inlines.Add(run);
}
}
Поскольку он работает со строками, я попытался сериализовать абзацы, но получил исключение «Обнаружен возможный цикл объекта».
Подробнее здесь: https://stackoverflow.com/questions/789 ... ker-thread