简体   繁体   中英

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. So by using hyperlink user can easily reached to desire paragraph in textfile/docx file etc.

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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