【发布时间】: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