简体   繁体   English

防止Winform应用程序冻结

[英]Prevent winform application from freezing

I'm Working on a small desktop app that search text in string and show the searched paragraph in richtextbox and also create hyperlink on it. 我正在使用一个小型桌面应用程序,该应用程序以字符串形式搜索文本并在richtextbox中显示搜索到的段落,并在其上创建超链接。 So by using hyperlink user can easily reached to desire paragraph in textfile/docx file etc. 因此,通过使用超链接,用户可以轻松地在textfile / docx文件等中达到所需的段落。

Question: While executing a for loop to create hyperlink on searched paragraphs and show it in richtextbox my interface is freezes I loose my control on form and form controls,I think I need to use some threading model for that, is there any idea, how can I proceed to solve the issue? 问题:在执行for循环以在搜索到的段落上创建超链接并将其显示在richtextbox中时,我的界面被冻结了。我松开了对窗体和窗体控件的控件,我想我需要为此使用一些线程模型,是否有任何想法,如何我可以继续解决这个问题吗?

Below is my code which I was try to create hyperlink in richtextbox also I tell you here, I am using devexpress richtextedit (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); 
            });
        }

Also I try below code but it wasn't solved my problem. 我也尝试下面的代码,但没有解决我的问题。

for (int i = 0; i < split.Length; i++)
        {
            Action showMethod = delegate() 
            { 
              linkRange = richEditControl1.Document.AppendText(split[i] + "\n\n"); 
              hyperlink = richEditControl1.Document.CreateHyperlink(linkRange); 
            };
        }

Use Async/Await feature. 使用异步/等待功能。

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.
        }
}

You may want to Reduce delay or increase it. 您可能希望减少延迟或增加延迟。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM