zoukankan      html  css  js  c++  java
  • 【NET多线程】C#多线程异步请求多个url地址

    异步测试代码

                System.Diagnostics.Debug.Print("start");
                new Thread(new ThreadStart(new Action(() =>
                {
                    for (int i = 0; i < 10; i++)
                    {
                        System.Diagnostics.Debug.Print(i + "
    ");
                    }
    
                    System.Diagnostics.Debug.Print("Thread over");
                }))).Start();
                System.Diagnostics.Debug.Print("Main over");

    输出

    "start"
    "Main over"
    "0
    "
    "1
    "
    "2
    "
    "3
    "
    "4
    "
    "5
    "
    "6
    "
    "7
    "
    "8
    "
    "9
    "
    "Thread over"

    效果是主线程已经结束了,子线程才开始

           var url = "http://h5.ktgj.com/";
    
                var list_task = new List<Task<string>>();
                for (int i = 0; i < 10; i++)
                {
                    var temp_url = url + i;
                    var task = Task.Run(async () =>
                    {
                        System.Diagnostics.Debug.Print("temp_url=" + temp_url);
                        var client = new System.Net.Http.HttpClient();
                        var html = await client.GetStringAsync(temp_url);
                        System.Diagnostics.Debug.Print("temp_url=" + temp_url + " is ok");
                        return html;
                    });
    
                    list_task.Add(task);
                }
    
                Task.WaitAll(list_task.ToArray());
    
                foreach (var item in list_task)
                {
                    System.Diagnostics.Debug.Print(item.Result);
                }

    Task.WaitAll()

    等所有请求都返回了html,才开始后续处理

                //await Task.WhenAll(task1, task2, task3);
    
                //ThreadPool.QueueUserWorkItem(_ =>
                //{
                //    Thread.Sleep(1000);
                //    Thread.Sleep(10); System.Diagnostics.Debug.Print("ThreadPool.QueueUserWorkItem");
                //});
    
                ////不使用await:Task多线程
                //Task.Run(() =>
                //{
                //    Thread.Sleep(1000);
                //    Thread.Sleep(10); System.Diagnostics.Debug.Print("Task.Run");
                //});
  • 相关阅读:
    sqlserver 分页
    sqlserver 用FOR XML PATH('')多行并成一列
    yarn的安装和使用
    redis安装及基本使用
    dbeaver 的界面乱码
    cypress测试框架(一)
    外网访问VMware虚拟机的Web服务---系列操作
    将博客搬至CSDN
    textgrid-python模块基础使用
    opencv通过mask掩码图合成两张图
  • 原文地址:https://www.cnblogs.com/jhli/p/9213615.html
Copyright © 2011-2022 走看看