多线程挂起UI?
Posted
技术标签:
【中文标题】多线程挂起UI?【英文标题】:Multi threading hangs UI? 【发布时间】:2019-07-08 09:28:19 【问题描述】:我正在使用多线程来使任务更快更流畅,当结果增加到 Richtextbox 时 UI 开始挂起,不知道为什么,我在线程中创建了一个 webbrowser,并在单线程中做一些其他的事情!
使用线程作为 STA(单线程类型)
这是代码的 sn-p !
foreach (string line in URLLMemoRichTxt.Lines)
string href = line;
if (href.Trim() != string.Empty)
//XtraMessageBox.Show(href);
if (StopGettingInnerLink == true)
AddLog("Getting links has been stopped successfully!");
StopGettingInnerLink = true;
break;
else if (StopGettingInnerLink == false)
AddLog("Getting links from " + href);
runBrowserThread( new Uri(href));
await Task.Delay(5000);
AddLog("Giving the tool some rest for 5 seconds ! ");
private void runBrowserThread(Uri url)
browserth = new Thread(() =>
var br = new WebBrowser();
br.ScriptErrorsSuppressed = true;
br.DocumentCompleted += browser_DocumentCompleted;
br.Navigate(url);
Application.Run();
);
browserth.SetApartmentState(ApartmentState.STA);
browserth.Start();
void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
var br = sender as WebBrowser;
string currentURL = br.Url.ToString();
if (br.Url == e.Url)
htmlElementCollection acollection = br.Document.GetElementsByTagName("a");
foreach (HtmlElement a in acollection)
string href = a.GetAttribute("href");
if (URLLMemoRichTxt.InvokeRequired)
URLLMemoRichTxt.Invoke((MethodInvoker)delegate ()
if (!URLList.Contains(href) && href.Trim() != string.Empty && !href.Contains(".jpg") && !href.Contains(".png") && !href.Contains(".gif") && !href.Contains(".jpeg"))
URLList.Add(href);
// URLListView.Items.Add(href);
// adding new link ino listview !
// URLListCountLBL.Text = URLListView.Items.Count.ToString();
URLLMemoRichTxt.Text += href + "\n";
URLListCountLBL.Text = URLLMemoRichTxt.Lines.Length.ToString();
// runbrowserinthread(href);
);
else
if (!URLList.Contains(href) && href.Trim() != string.Empty && !href.Contains(".jpg") && !href.Contains(".png") && !href.Contains(".gif") && !href.Contains(".jpeg"))
URLList.Add(href);
// URLListView.Items.Add(href);
URLLMemoRichTxt.Text += href + "\n";
URLListCountLBL.Text = URLLMemoRichTxt.Lines.Length.ToString();
// GetInnerLink(href);
AddLog("All links has been scrapped successfully for \r\n" + currentURL);
Application.ExitThread(); // Stops the thread
【问题讨论】:
【参考方案1】:自己已经找到了解决方案:
替换:
URLLMemoRichTxt.Text += href + "\n";
与:
URLLMemoRichTxt.AppendText(Environment.NewLine + href);
【讨论】:
以上是关于多线程挂起UI?的主要内容,如果未能解决你的问题,请参考以下文章