Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/270.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何并行执行web请求?_C#_Asp.net Core - Fatal编程技术网

C# 如何并行执行web请求?

C# 如何并行执行web请求?,c#,asp.net-core,C#,Asp.net Core,如何并行执行此代码?我尝试在线程中执行,但请求仍按顺序执行。我是并行编程新手,我将非常高兴您的帮助 public async Task<IList<AdModel>> LocalBitcoins_buy(int page_number) { IList<AdModel> Buy_ads = new List<AdModel>(); string next_page_url; strin

如何并行执行此代码?我尝试在线程中执行,但请求仍按顺序执行。我是并行编程新手,我将非常高兴您的帮助

    public async Task<IList<AdModel>> LocalBitcoins_buy(int page_number)
    {
        IList<AdModel> Buy_ads = new List<AdModel>();
        string next_page_url;
        string url = "https://localbitcoins.net/buy-bitcoins-online/.json?page=" + page_number;
        WebRequest request = WebRequest.Create(url);
        request.Method = "GET";
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                JObject json = JObject.Parse(await reader.ReadToEndAsync());
                next_page_url = (string) json["pagination"]["next"];
                int counter = (int) json["data"]["ad_count"];
                for (int ad_list_index = 0; ad_list_index < counter; ad_list_index++)
                {
                    AdModel save = new AdModel();
                    save.Seller = (string) json["data"]["ad_list"][ad_list_index]["data"]["profile"]["username"];
                    save.Give = (string) json["data"]["ad_list"][ad_list_index]["data"]["currency"];
                    save.Get = "BTC";
                    save.Limits = (string) json["data"]["ad_list"][ad_list_index]["data"]["first_time_limit_btc"];
                    save.Deals = (string) json["data"]["ad_list"][ad_list_index]["data"]["profile"]["trade_count"];
                    save.Reviews = (string) json["data"]["ad_list"][ad_list_index]["data"]["profile"]["feedback_score"];
                    save.PaymentWindow = (string) json["data"]["ad_list"][ad_list_index]["data"]["payment_window_minutes"];
                    Buy_ads.Add(save);
                }
            }
        }
        Console.WriteLine(page_number);
        return Buy_ads;
    }
公共异步任务本地比特币购买(整数页码)
{
IList Buy_ads=新列表();
字符串“下一页”\u url;
字符串url=”https://localbitcoins.net/buy-bitcoins-online/.json?page=“+页码;
WebRequest=WebRequest.Create(url);
request.Method=“GET”;
使用(WebResponse=await request.GetResponseAsync())
{
使用(var reader=newstreamreader(response.GetResponseStream())
{
JObject json=JObject.Parse(wait reader.ReadToEndAsync());
下一页url=(字符串)json[“分页”][“下一页”];
int计数器=(int)json[“数据”][“ad_计数”];
for(int ad_list_index=0;ad_list_index
我在谷歌上搜索并找到了这些链接。似乎
WebRequest
无法并行执行请求。我还尝试使用
WebRequest
并行发送多个请求,但由于某些原因
WebRequest
没有并行发送请求

但当我使用类时,它并行处理请求。尝试使用
HttpClient
而不是像Microsoft那样使用
WebRequest

因此,首先,您应该使用
HttpClient
进行web请求。


然后您可以使用下一种方法并行下载页面:

public static IList<AdModel> DownloadAllPages()
{
    int[] pageNumbers = getPageNumbers();
    // Array of tasks that download data from the pages.
    Task<IList<AdModel>>[] tasks = new Task<IList<AdModel>>[pageNumbers.Length];

    // This loop lauches download tasks in parallel.
    for (int i = 0; i < pageNumbers.Length; i++)
    {
        // Launch download task without waiting for its completion.
        tasks[i] = LocalBitcoins_buy(pageNumbers[i]);
    }

    // Wait for all tasks to complete.
    Task.WaitAll(tasks);

    // Combine results from all tasks into a common list.
    return tasks.SelectMany(t => t.Result).ToList();
}
公共静态IList下载所有页面()
{
int[]pageNumbers=getPageNumbers();
//从页面下载数据的任务数组。
任务[]任务=新任务[PageNumber.Length];
//此循环并行启动下载任务。
for(int i=0;it.Result).ToList();
}

当然,您应该在这个方法中添加错误处理。

我建议您仔细研究这篇文章:

它有一个教程,正是你想要做的:同时下载多个页面

WebRequest不是有意与getResponse异步工作的。它还有第二个方法:getResponseAsync()


为了让线程弄湿你的脚趾,你也可以用插入式替换foreach和for循环:

如果next\u page\u url不为空,你会一次又一次地请求相同的页码。这不会导致无限循环吗?为什么你要尝试执行这个并行,你这样做的目的是什么?我需要从60页中获取数据,如果我按顺序执行,这将花费很多时间。因此,我想启动一个并行过程。是否要使用参数
页码
的不同值并行运行方法
LocalBitcoins\u buy
?如果是这样,请发布您当前用于从页面获取数据的方法(用于从60页获取数据的方法)?谢谢,将您的代码粘贴到我的项目中。所有请求继续同步执行。@请记住,我尝试使用WebRequest和提供的方法DownloadAllPages发送多个请求。由于某些原因,WebRequest没有并行发出请求。但当我使用类时,它并行处理请求。尝试使用HttpClient而不是WebRequest。微软也开始使用HttpClient。请告诉我HttpClient是否能帮助您。@Clear Mind我在谷歌上搜索并找到了这个链接。WebRequest似乎无法并行执行请求。因此,请尝试使用。@Clear Mind我更新了我的帖子,以包含所有必需的信息。