0

IP アドレス プロバイダーの URL の 1 つからパブリック IP アドレスを取得する必要があります。問題は、これらのサービスは信頼できないため、別の URL にフォールバックする必要があることです。最大のパフォーマンスを得るために、すべてのサービス プロバイダーに対して WebRequest を同時に開始し、最初に応答したプロバイダーの結果を考慮したいと考えています。

これは私が書いたコードです。それは絶対にうまくいきます。しかし、私は使用しEventWaitHandleました。WaitHandleこれが正しい方法であるかどうか、または使用せずに(async/awaitのみを使用して)同じことを行うことが可能かどうかを知りたいだけですか?

    private static readonly string[] IpProviders = new string[] {
            "http://ipinfo.io/ip", "http://canihazip.com/s",
            "http://icanhazip.com",  "http://bot.whatismyipaddress.com" };


    private static string _publicIp = null;
    public static string PublicIp
    {
        get
        {
            if (_publicIp == null)
            {
                _publicIp = FetchPublicIp();
            }
            return _publicIp;
        }
    }

    private static string FetchPublicIp()
    {
        using (MyResetEvent manualEvent = new MyResetEvent())
        {
            foreach (string providerUrl in IpProviders)
            {
                FetchPublicIp(providerUrl).
                    ContinueWith(x => OnResult(x.Result, manualEvent));
            }

            int looped = 0;
            do
            {
                manualEvent.WaitOne();
                lock (manualEvent)
                {
                    if (!string.IsNullOrWhiteSpace(manualEvent.Result))
                    {
                        return manualEvent.Result;
                    }
                    else
                    {
                        manualEvent.Reset();
                    }
                    looped = manualEvent.Count;
                }
            } while (looped < IpProviders.Length);
        }
        return null;
    }

    private static async Task<string> FetchPublicIp(string providerUrl)
    {
        string externalip;
        try
        {
            externalip = await new WebClient().DownloadStringTaskAsync(providerUrl);
        }
        catch (WebException ex)
        {
            Debug.WriteLine(ex);
            externalip = null;
        }

        if (!string.IsNullOrWhiteSpace(externalip))
        {
            System.Net.IPAddress ip;
            if (System.Net.IPAddress.TryParse(externalip.Trim(), out ip))
            {
                return ip.ToString();
            }
        }
        return null;
    }

    private static void OnResult(string s, MyResetEvent manualEvent)
    {
        try
        {
            lock (manualEvent)
            {
                if (manualEvent.Result == null)
                {
                    manualEvent.Result = s;
                }
                manualEvent.Count++;
                manualEvent.Set();
            }
        }
        catch (ObjectDisposedException ex)
        {
            Debug.WriteLine(ex);
        }
    }

MyResetEvent クラスは次のとおりです。

internal class MyResetEvent : EventWaitHandle
{
    public MyResetEvent()
        : base(false, EventResetMode.ManualReset)
    {

    }
    public string Result { get; set; }
    public int Count { get; set; }
}
4

2 に答える 2

4

あなたはこのように考えすぎています。TPL はあなたを助けるためにあります。あなたと戦うためではありません!

async Task<string> TakeFirstResponse(string[] urls)
{
    return await await Task.WhenAny(
            urls.Select(async url => 
                await new WebClient().DownloadStringTaskAsync(url)));
}

なぜダブルが待っているのですか?は仕様によりTask.WhenAnya を返しますTask<Task<T>>

于 2015-04-10T04:25:06.097 に答える