【问题标题】:How to set in Silverlight WebClient timeout?如何在 Silverlight WebClient 中设置超时?
【发布时间】:2011-10-20 13:43:08
【问题描述】:

我在 Silverlight 应用程序中使用 WebClient 来访问 REST 服务。它的异步调用数量未知。 很酷的是,您可以订购您的请求和响应!响应与他们的请求相匹配!这是必要的,因为您不知道响应将以什么顺序返回。

但是如何让我的 WebClient 调用“超时”?让我们说 15 秒 我想坚持 WebClient/this code with delegates/lambda。我知道 WebRequest 类有一个超时属性,但我不确定是否可以用 WebRequest 替换 WebClient 但保留该功能。

int maxRequests = list_S.Count;
// amount of URI
        foreach (string item in list_S)
        {
            bool isValid = Uri.IsWellFormedUriString(item, UriKind.Absolute);
            Uri uriTest;
            if(isValid) //if it is valid Uri, send request
            {
                WebClient wc = new WebClient();
                wc.DownloadStringCompleted += (s, args) =>
                {
                    if (args.Error == null)
                    {
                        dict.Add((int)args.UserState, args.Result);

                    }
                    //here you test if it is the last request... if it is, you can
                    //order the list and use it as you want 
                    if (dict.Count == maxRequests)
                    {
                        var orderedResults = dict.OrderBy(a => a.Key);
                    }
                    closeTabitem_SensorSource();
                };
                wc.DownloadStringAsync(new Uri(item), i++);
            }
            else
            {
                MessageBox.Show("Uri FAIL!: " + item);
            }
        }

【问题讨论】:

    标签: silverlight asynchronous httpwebrequest webclient


    【解决方案1】:

    WebRequest 也不提供管理请求超时的方法。

    您需要采取的方法是将WebClient 与您自己的基于DispatcherTimer 的代码结合使用,该代码将调用WebClient CancelAsync 方法。

    【讨论】:

    • 如果我没记错的话,有一个内置的超时时间(大约 30 秒,从内存中。)所以如果你想要更短的超时时间,这种方法会起作用,但如果你想要更长的超时时间就不行.
    • @Drew:我认为你错了。在服务器上延迟 5 分钟进行测试,我无法让 BrowserHttp 和 ClientHttp 堆栈超时。当然,客户端和服务器上的代码之间可能存在各种其他设备,从而导致延迟,这可能会干预并引发超时。但是,Silverlight 似乎没有内置超时,或者它可能过大。 30秒有点小气。
    • @AnthonyWJones,感谢您对此的纠正。它与我现在的工作相关,因此非常有帮助。
    猜你喜欢
    • 2018-02-24
    • 2012-09-01
    • 2018-08-06
    • 1970-01-01
    • 2020-10-12
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多