簡體   English   中英

阻塞主線程,直到完成所有異步調用

[英]blocking main thread until all async calls are done

這個問題對於如何執行異步HttpWebRequest有很好的答案

我有一個50k + URL的列表,我想用這種方法異步獲取。 我遇到的問題是主線程會完成並在所有異步請求完成之前退出。

我發現ManualResetEvent可以用於WaitOne() ,並可以在回調方法上調用Set() 如果我僅執行一個請求,這將非常有用。 不確定如何處理許多請求。

您可以使用TPL:

using System;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

class Program
{
    static void Main(string[] args)
    {
        var urls = new[] 
        { 
            "http://www.google.com", 
            "http://www.yahoo.com" 
        };

        var tasks = urls.Select(url =>
        {
            var request = WebRequest.Create(url);
            return Task
                .Factory
                .FromAsync<WebResponse>(request.BeginGetResponse, request.EndGetResponse, url)
                .ContinueWith(t =>
                {
                    if (t.IsCompleted)
                    {
                        using (var stream = t.Result.GetResponseStream())
                        using (var reader = new StreamReader(stream))
                        {
                            Console.WriteLine("-- Successfully downloaded {0} --", t.AsyncState);
                            Console.WriteLine(reader.ReadToEnd());
                        }
                    }
                    else if (t.IsFaulted)
                    {
                        Console.WriteLine("There was an error downloading {0} - {1}", t.AsyncState, t.Exception);
                    }
                });
        }).ToArray();

        Task.WaitAll(tasks);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM