我已经制作了一个不使用Web浏览器类的Web浏览器(在文本框上显示html响应)。我通过在CREATE NEW TAB事件上编程来动态创建标签页。现在我希望我的浏览器为每个标签创建一个单独的线程。我使用asyn并等待每个选项卡的新线程的实现,但它给了我错误“跨线程操作无效:控件'Form1'从一个线程访问,而不是它创建的线程。”这是我的代码:
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");
}
});
}
}
}