0

我需要从 IP 地址提供商 URL 之一获取我的公共 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.WhenAny返回Task<Task<T>>

于 2015-04-10T04:25:06.097 回答
0

@Bas 的答案是正确的(实际上您可能应该接受它),但我想提供一个使用我的Flurl库的更简洁的替代方案:

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

Flurl.Http由 支持HttpClient,它比 更新且通常更可取WebClient所有其他条件都相同。

于 2015-04-12T15:01:45.057 回答