public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
public void beginpa()
{
WebClient wc = new WebClient();
var vb = wc.DownloadData("https://www.baidu.com/");
var str = System.Text.Encoding.UTF8.GetString(vb);
baochun(str);
}
/// <summary>
/// 锁
/// </summary>
private static object obj = new object();
/// <summary>
/// 读写文件
/// </summary>
/// <param name="str"></param>
public void baochun(string str)
{
str = str.Substring(0, 12);
lock (obj)
{
using (FileStream filst = new FileStream(@"c:\user.txt", FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(filst))
{
sw.WriteLine(str);
sw.Flush();
sw.Close();
}
}
}
}
/// <summary>
/// 取消线程
/// </summary>
CancellationTokenSource tsource = new CancellationTokenSource();
/// <summary>
/// 创建线程对象
/// </summary>
List<Task> lt = new List<Task>();
/// <summary>
/// 开始抓取
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
//获取线程个数
int count = Convert.ToInt32(this.textBox1.Text);
//循环个数开启线程
for (int i = 0; i < count; i++)
{
//创建线程并 加到取消线程对象
Task task = new Task(() =>
{
Thread.Sleep(4000);
try
{
if (tsource.IsCancellationRequested == true) // 表示已经取消了线程
{
//抛出一个异常组织线程的执行。
tsource.Token.ThrowIfCancellationRequested();
}
beginpa();
}
catch (OperationCanceledException ex)
{
MessageBox.Show("线程已取消");
//throw;
}
}, tsource.Token);
lt.Add(task);
}
foreach (var item in lt)
{
item.Start();
this.listBox1.Items.Add("线程" + item.Id + "状态:" + item.Status);
}
}
private void button2_Click(object sender, EventArgs e)
{
//取消线程
tsource.Cancel();
foreach (var item in lt)
{
this.listBox1.Items.Add("线程" + item.Id + "状态:" + item.Status);
}
}
}