using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
textBox1.Text = "place url hear";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
Task.Factory.StartNew(() => get_url_contents(textBox1.Text)).ContinueWith(t => t.Id, TaskScheduler.FromCurrentSynchronizationContext());
}
private void get_url_contents(string url)
{
var doc = new HtmlWeb().Load(url);
HtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//a");
foreach(HtmlNode node in nodes)
{
listView1.Items.Add(node.InnerText);
}
}
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
使用Windows Forms和在練習C#,林相當新的這種語言,但知道一點蟒蛇林。
基本上,即時嘗試要做的是,您在textBox1
上輸入url
,當您點擊button1
時,它會轉到該網址並提取所有鏈接的文本。
和append
這些結果listView1
但我不斷收到此錯誤
錯誤消息:
Additional information: Cross-thread operation not valid: Control 'listView1' accessed from a thread other than the thread it was created on.
我們該如何糾正呢?
我得到了這個工作。通過使返回的東西,然後在'ContinueWith'方法這樣運行它的另一種方法: 'ContinueWith(T => other_method_that_processes_results(t.Result)..........)' 然而,我想只用一種方法就可以做到這一點。但顯然這是不允許的 – Zion
在SO上提供了正確的解決方案太多次。讓我們假裝OP已經搜索,並發現它沒有什麼有趣...或簡單downvote的問題... –