C#入门-并行编程

就当是做个笔记吧。

课堂题目:做一个窗体应用程序,接收用户输入的关键字,用户点击搜索时使用baidu,bing等搜索引擎搜索关键字,从搜索结果中,摘抄文字部分的前200个字,分别显示到两个多行文本框内。
请使用多线程方式、并行编程或者异步编程方式完成任务。

说来惭愧,参考同学的代码才写出来的,我果然是个编程小菜鸡。

这是一个窗体应用程序

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 System.Windows.Forms;
using System.Net;

namespace WindowsFormsApp13
{
    public partial class Form1 : Form
    {
        private delegate void MyDelegate();
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Task task_baidu = new Task(() => { Search_baidu("https://www.baidu.com/baidu?wd=" + textBox1.Text); }) ;
            Task task_bing = new Task(() => { Search_bing("https://cn.bing.com/search?form=MOZTSB&pc=MOZI&q=" + textBox1.Text); });
            task_baidu.Start();
            task_bing.Start();
        }
        private void Search_baidu(string url)           // baidu
        {
            WebClient webClient = new WebClient();
            byte[] recvdata = webClient.DownloadData(url);       // 指定url下载数据到byte数组中
            string response = Encoding.UTF8.GetString(recvdata); // 获取UTF-8类型编码
            this.BeginInvoke(new MyDelegate(() => { textBox_baidu.Text = response.Substring(0, 100); }));   // 将转换后的数据填入textBox
        }
        private void Search_bing(string url)           // bing
        {
            WebClient webClient = new WebClient();
            byte[] recvdata = webClient.DownloadData(url);
            string response = Encoding.UTF8.GetString(recvdata);
            this.BeginInvoke(new MyDelegate(() => { textBox_bing.Text = response.Substring(0, 100); }));
        }
    }
}

猜你喜欢

转载自blog.csdn.net/MARS_098/article/details/105767280