【发布时间】:2016-11-11 09:57:42
【问题描述】:
我正在尝试什么
在我的 WPF 中,我抓取我的内部网络并查看是否可以访问 IP/URL。所以我用DownloadStringAsync 循环调用255 个IP。现在,每当我收到响应或超时时,我都想更新我的进度条(最大值为 255)。当我看到进度条在移动时,我的代码似乎适用于前 x 个(我相信大概是 10-15 个)IP
调用循环
try
{
while (i < 255)
{
var client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(GetInfo);
client.DownloadStringAsync(new Uri("http://" + myIPNet + "." + i + ":1400/status/topology"));
i++;
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
GetInfo 函数
private void GetInfo(object sender, DownloadStringCompletedEventArgs e)
{
/* Each call, count up Global Ip Counter and move progressBar */
countIps++;
pbSearch.Value = countIps;
/* Do Stuff with e.Result */
...
/* Check if we have all IPs in net already */
if (countIps == 255)
{
/* Reset progressBar */
pbSearch.Value = 0;
/* Enable Button */
btnGetAll.IsEnabled = true;
}
}
我找到了这个Asynchronous File Download with Progress Bar,我想我理解这个答案https://stackoverflow.com/a/9459441/1092632,但是这个进度条更新了一个正在进行的下载,关于如何将这个“转换”到我的案例有什么想法吗?
【问题讨论】:
-
我发现您的代码存在多个问题。您在循环中创建了一个
WebClient,但不释放它(它是一个IDisposable)。您想直接从您的模型代码更新ProgressBar,但这不是 WPF 应用程序的设计方式 - 请改用 MVVM 方法和数据Bindings。
标签: c# wpf asynchronous