I have made a web browser without using web browser class(Displaying html response on textbox).I m dynamically creating tab pages by programming on CREATE NEW TAB event.Now i want my browser to have a separate thread for each tab.I used asyn and await for the implementation of new thread for each tab but it gave me error "Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on." Here is my code:
async void navigateToPage(string s)
{
Uri uri = null;
if (!Uri.TryCreate(s, UriKind.Absolute, out uri) || null == uri)
{
//Invalid URL
MessageBox.Show("Please Enter valid URL");}
else
{
HttpWebRequest request = WebRequest.Create(s) as HttpWebRequest;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
// Contains protocol headers associated with a request or response
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
if (focussedTab == null)
{
textBox1.Text = responseText;
}
else
{
if (focussedTab.Controls.ContainsKey("outputBox"))
{
TextBox textBox = (TextBox)focussedTab.Controls["outputBox"];
textBox.Text = responseText;
}
}
using (tw = new StreamWriter(@"history.txt", true))
{ //writing history on a file
tw.WriteLine(s+"" +System.DateTime.Now);
tw.Close();
}
// adding url to the list for the back/fwd
backStack.Push(s);
fwdStack.Clear();
}
}
else if (response.StatusCode == HttpStatusCode.NotFound)
{
MessageBox.Show("Not Found");
}
else if (response.StatusCode == HttpStatusCode.Forbidden)
{
MessageBox.Show("Forbidden");
}
else if (response.StatusCode==HttpStatusCode.BadRequest)
{
MessageBox.Show("Bad Request");
}
await DisplayNewTab();
}
Task DisplayNewTab()
{
return Task.Factory.StartNew(() =>
{
try
{
TabPage newTab = new TabPage();
newTab.Name = "tab";
newTab.Text = "New Tab";
TextBox txtbx = new TextBox();
txtbx.Name = "outputBox";
txtbx.Multiline = true;
txtbx.Size = new System.Drawing.Size(754, 259);
tb1.Text = "https://";
newTab.Controls.Add(txtbx);
focussedTab = newTab;
tabControl1.TabPages.Add(newTab);
}
catch (Exception excMsg)
{
MessageBox.Show(excMsg.Message.ToString(), "Error");
}
});
}
}
}