我在 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);
}
}
最佳答案
WebRequest
也不提供管理请求超时的方法。
您需要采取的方法是将 WebClient
与您自己的基于 DispatcherTimer
的代码结合使用,该代码将调用 WebClient
CancelAsync
方法。
关于silverlight - 如何在Silverlight WebClient中设置超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7836841/