我正在使用多线程来执行一些任务,但是当我启动进程时,UI 挂起,我在另一个解决方案中使用相同的方法并且它工作正常!
这是一个片段。我也尝试使用 HTMLagality,但我不认为这是原因,此方法使用普通的 http 网络请求
使用 C#、VS 2015、.Net Framework 4.6.1
var th = new Thread(() =>
{
if (LinksToGetEmailsListView.InvokeRequired)
{
LinksToGetEmailsListView.Invoke((MethodInvoker)delegate ()
{
foreach (ListViewItem link in LinksToGetEmailsListView.Items)
{
#region Extracting Emails from Html Page
//instantiate with this pattern
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(link.Text);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
string file;
var response = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
file = sr.ReadToEnd();
}
string[] result = GetEmailsFromWebContent(file);
foreach (string r in result)
{
XtraMessageBox.Show(r);
}
#endregion
// string[] result = GetEmailsFromWebContent(iWeb.Load(link.Text).DocumentNode.OuterHtml);
link.Focused = true;
// foreach (string email in result)
//{
// XtraMessageBox.Show(email);
//}
}
});
}
else
{
foreach (ListViewItem link in LinksToGetEmailsListView.Items)
{
#region Extracting Emails from Html Page
//instantiate with this pattern
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(link.Text);
httpWebRequest.UseDefaultCredentials = true;
httpWebRequest.UserAgent = @"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)";
httpWebRequest.Method = WebRequestMethods.Http.Get;
httpWebRequest.Accept = "application/json; charset=utf-8";
string file;
var response = (HttpWebResponse)httpWebRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
file = sr.ReadToEnd();
}
string[] result = GetEmailsFromWebContent(file);
foreach (string r in result)
{
XtraMessageBox.Show(r);
}
#endregion
}
}
});
th.SetApartmentState(ApartmentState.STA);
th.Start();
最佳答案
您实际上是在 UI 线程上运行所有代码,这就是 UI 挂起的原因。你启动了一个辅助线程,但随后你立即做了一个InvokeRequired
/Invoke
查看。出色地;它将是必需的,因为您在辅助线程上。所以...您在辅助线程中做的第一件事就是将工作推回到 UI 线程。
您可能想推迟 Invoke
直到您真正准备好更新 UI,即在最后一个 XtraMessageBox.Show
前后(可能还有周围的 foreach
)。重要的是:将其从方法的前面移除。
关于c# - 使用线程 C# 时 UI 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54512746/