【问题标题】:ServicePointManager.FindServicePoint blocksServicePointManager.FindServicePoint 块
【发布时间】:2019-03-14 13:48:14
【问题描述】:

我正在调用这个方法:

ServicePoint sp = ServicePointManager.FindServicePoint(mRequest.RequestUri, this.MapDataWebProxy);

用于获取服务点,但是当没有可用的互联网连接时,该方法不会返回。

关于如何防止这种情况或设置超时的任何想法?

【问题讨论】:

  • 使用Task?你可以设置超时吗?
  • var task = Task.Run(() => SomeMethod(input)); if (task.Wait(TimeSpan.FromSeconds(10))) return task.Result; else throw new Exception("Timed out");

标签: c# http servicepoint


【解决方案1】:

您可以在调用该方法之前尝试验证 Internet 连接。可以这样做:

[DllImport("wininet.dll")]
    private extern static bool InternetGetConnectedState(out int Description, int ReservedValue);

    //Creating a function that uses the API function...
    public static bool IsConnectedToInternet()
    {
        int Desc;
        return InternetGetConnectedState(out Desc, 0);
    }

    public ServicePoint GetServicePoint()
    {
        if (!IsConnectedToInternet())
        {
            return null;
        }
        return ServicePointManager.FindServicePoint(mRequest.RequestUri, this.MapDataWebProxy);
    }

还可以通过其他方式检查 Internet。不使用“wininet.dll”库:What is the best way to check for Internet connectivity using .NET?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 2011-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-27
    相关资源
    最近更新 更多