[英]Prevent winform application from freezing
我正在使用一个小型桌面应用程序,该应用程序以字符串形式搜索文本并在richtextbox中显示搜索到的段落,并在其上创建超链接。 因此,通过使用超链接,用户可以轻松地在textfile / docx文件等中达到所需的段落。
问题:在执行for循环以在搜索到的段落上创建超链接并将其显示在richtextbox中时,我的界面被冻结了。我松开了对窗体和窗体控件的控件,我想我需要为此使用一些线程模型,是否有任何想法,如何我可以继续解决这个问题吗?
以下是我尝试在richtextbox中创建超链接的代码,我在这里也告诉您,我正在使用devexpress richtextedit(richtextbox)。
for (int i = 0; i < split.Length; i++)
{
Task.Factory.StartNew(() =>
{
linkRange = richEditControl1.Document.AppendText(split[i] + "\n\n");
hyperlink = richEditControl1.Document.CreateHyperlink(linkRange);
});
}
我也尝试下面的代码,但没有解决我的问题。
for (int i = 0; i < split.Length; i++)
{
Action showMethod = delegate()
{
linkRange = richEditControl1.Document.AppendText(split[i] + "\n\n");
hyperlink = richEditControl1.Document.CreateHyperlink(linkRange);
};
}
使用异步/等待功能。
private async void YourMethod()
{
//...
for (int i = 0; i < split.Length; i++)
{
linkRange = richEditControl1.Document.AppendText(split[i] + "\n\n");
hyperlink = richEditControl1.Document.CreateHyperlink(linkRange);
await Task.Delay(50); // wait a moment here so win can perform other operations and will not freeze.
}
}
您可能希望减少延迟或增加延迟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.