gpt4 book ai didi

c# - 如何从后台线程访问 WPF 控件

转载 作者:太空宇宙 更新时间:2023-11-03 19:01:08 26 4
gpt4 key购买 nike

我有一个 RichTextBox,我正在尝试查找并突出显示与用户提供的查询匹配的所有单词。我的代码有效,但对于相当大的文档,它会挂起 UI,因为一切都在 UI 线程上完成。

List<TextRange> getAllMatchingRanges(String query)
{
TextRange searchRange = new TextRange(ricthBox.Document.ContentStart, ricthBox.Document.ContentEnd);
int offset = 0, startIndex = 0;
List<TextRange> final = new List<TextRange>();
TextRange result = null;

while (startIndex <= searchRange.Text.LastIndexOf(query))
{
offset = searchRange.Text.IndexOf(query, startIndex);

if (offset < 0)
break;
}

for (TextPointer start = searchRange.Start.GetPositionAtOffset(offset); start != searchRange.End; start = start.GetPositionAtOffset(1))
{
if (start.GetPositionAtOffset(query.Length) == null)
break;
result = new TextRange(start, start.GetPositionAtOffset(query.Length));
if (result.Text == query)
{
break;
}
}
if (result == null)
{
break;
}
final.Add(result);

startIndex = offset + query.Length;
}

return final;

}

这将返回我可以突出显示的文本范围列表,但我无法在后台线程上执行它,因为它会抛出异常,因为我会尝试在未创建它的线程上访问 richTextbox 的文档.

最佳答案

一个选项是 Dispatcher's background priority .让突出显示在后台发生,而不会阻塞 UI 线程。

Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => {// Do your highlighting}));

关于c# - 如何从后台线程访问 WPF 控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35629591/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com