Не получается обновить UI из другого потока
Вызываю все через диспетчер, считывание работает нормально, а вот присваивание вызывает исключение Вызывающий поток не может получить доступ к данному объекту, так как владельцем этого объекта является другой поток (место пометил комментарием)
private void Button_Click_3(object sender, RoutedEventArgs e)
{
autosearch = !autosearch;
Thread t = new Thread(new ThreadStart(Auto_Search));
t.Start();
}
private void Auto_Search()
{
bool chk = false;
(int, bool) png = (0, false);
CheckBox1.Dispatcher.Invoke(new Action(() => { chk = (bool)CheckBox1.IsChecked; }));
Ping.Dispatcher.Invoke(new Action(() => { png.Item2 = int.TryParse(Ping.Text, out png.Item1); }));
Paragraph par = Generate();
main_String.Dispatcher.Invoke(new Action(() => { main_String.Document = new FlowDocument(par); }));//тут исключение
string st = "";
main_String.Dispatcher.Invoke(new Action(() => { st = new TextRange(main_String.Document.ContentStart, main_String.Document.ContentEnd).Text; }));
Random rand = new Random();
int pos1 = rand.Next(st.Length);
int pos2 = rand.Next(st.Length);
if (pos1 > pos2)
{
int temp = pos1;
pos1 = pos2;
pos2 = temp;
}
if (chk && png.Item2)
{
while (autosearch)
{
substring.Dispatcher.Invoke(new Action(() => { substring.Text = st.Substring(pos1, pos2 - pos1); }));
(int, int) indexs = Search(out long time);
if (indexs != (0, 0))
{
string s1 = hash.main_string.Substring(indexs.Item1, indexs.Item2 - indexs.Item1);
Paragraph p = new Paragraph();
p.Inlines.Add(new Run(hash.main_string.Substring(0, indexs.Item1)));
p.Inlines.Add(new Run(s1) { Foreground = Brushes.Red });
p.Inlines.Add(new Run(hash.main_string.Substring(indexs.Item2)));
main_String.Dispatcher.Invoke(new Action(() => { main_String.Document = new FlowDocument(par); }));
Comment_String.Dispatcher.Invoke(new Action(() =>
{
Comment_String.Text = $"Подстрока была найдена.\nВремя поиска составило: {time} миллисекунд";
Comment_String.Text += $"\nИндекс начала подстроки {indexs.Item1}, индекс конца {indexs.Item2}, длинна строки {indexs.Item2 - indexs.Item1}";
}));
}
else
{
Comment_String.Dispatcher.Invoke(new Action(() => { Comment_String.Text = $"Данной подстроки нет в основной строке\nВремя поиска составило: {time} миллисекунд"; }));
}
if (png.Item2)
{
Thread.Sleep(png.Item1 * 1000);
}
else
{
Thread.Sleep(1500);
}
}
}
}