如何在Silverlight WebClient中设置超时?
我在 Silverlight 应用程序中使用 WebClient 来访问 REST 服务。其异步调用数量未知。 很酷的是,您可以订购您的请求和响应!响应与他们的请求相匹配!这是必要的,因为您不知道响应将以什么顺序返回。
但是我如何获得 WebClient 通话的“超时”呢?假设 15 秒 我想坚持使用 WebClient/带有 delegate/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);
}
}
I use WebClient in a Silverlight Appliction to access REST Services. Its an unknown amount of asynchronous calls.
The cool thing is, you can order your requests and responses! the responses are matched to theirs requests! This is necessary, because you do not know in what order the responses will come back.
But how do i get a "timeout" for my calls with WebClient? lets say 15 sec
I would like kinda to stick to WebClient/this code with delegates/lambda. I know there is a timeout property with WebRequest class, but i am not sure if just can replace WebClient with WebRequest but keep the functionality.
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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
WebRequest
也不提供管理请求超时的方法。您需要采取的方法是将
WebClient
与您自己的基于DispatcherTimer
的代码结合使用,该代码将调用WebClient
CancelAsync方法。
The
WebRequest
does not provide a means for managing request timeouts either.The approach you need to take is to use
WebClient
in conjunction with your own code based on aDispatcherTimer
that will call theWebClient
CancelAsync
method.