本帖最后由 hacker 于 2017-3-6 16:38 编辑
需求:使用多线程,将HttpHelper获取的数据动态的更新到Listview中,不知道哪里写的不对,启动后发现UI卡死。
[C#] 纯文本查看 复制代码 using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using CsharpHttpHelper;
using CsharpHttpHelper.Enum;
namespace MutiThread
{
public partial class Form1 : Form
{
// 定义委托类
public delegate void DEUpdateListView(int i, string str);
// 声明一个委托对象
DEUpdateListView DEUpdateList;
public Form1()
{
InitializeComponent();
// 初始化委托对象, 绑定委托方法
DEUpdateList = new DEUpdateListView(UpdateListviewMethod);
}
//
public string HttpServer() {
HttpHelper http = new HttpHelper();
HttpItem item = new HttpItem()
{
URL = "http://1212.ip138.com/ic.asp",//URL 必需项
Method = "GET",//URL 可选项 默认为Get
Timeout = 100000,//连接超时时间 可选项默认为100000
ReadWriteTimeout = 30000,//写入Post数据超时时间 可选项默认为30000
IsToLower = false,//得到的HTML代码是否转成小写 可选项默认转小写
Cookie = "",//字符串Cookie 可选项
UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0",//用户的浏览器类型,版本,操作系统 可选项有默认值
Accept = "text/html, application/xhtml+xml, */*",// 可选项有默认值
ContentType = "text/html",//返回类型 可选项有默认值
Referer = "",//来源URL 可选项
Allowautoredirect = false,//是否根据301跳转 可选项
AutoRedirectCookie = false,//是否自动处理Cookie 可选项
Postdata = "",//Post数据 可选项GET时不需要写
ResultType = ResultType.String,//返回数据类型,是Byte还是String
};
HttpResult result = http.GetHtml(item);
string html = result.Html;
string cookie = result.Cookie;
return html;
}
// 更新Listview方法
public void UpdateListviewMethod(int i, string str) {
Lsv_Thread.Items.SubItems[3].Text = HttpServer();
}
//
public void CallUpdateListview() {
for (int i = 0; i < Lsv_Thread.Items.Count; i++) {
this.BeginInvoke(DEUpdateList, i, "开始");
}
}
// 初始化Listview
public void InitListview()
{
for (int j = 0; j < 100; j++)
{
Lsv_Thread.Items.Add(new ListViewItem(new string[] { j.ToString(), "", "", "" }));
}
}
private void Btn_Start_Click(object sender, EventArgs e)
{
Thread th = new Thread(new ThreadStart(delegate {
CallUpdateListview();
}));
th.Start();
}
private void Form1_Load(object sender, EventArgs e)
{
InitListview();
}
}
} |