I am using multithreading to do some tasks but when I start the process, the UI hangs, I am using the same method in another solution and its working fine!
Here is a snippet. I tried to use HTMLagality as well, but I don't think this is the reason, this method uses the normal http web request
Using 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 Threadwhere all UI-related behaviors should be placed. On your sample code you are creating a new thread and you're trying to perform UI-related actions such asXtraMessageBox.Show(r);. Make sure that it runs on the UI thread instead. Try looking up on how to invoke to the UI thread.