[英]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.