我在一个下载系统上工作,该系统一次最多下载 4 个文件,如果下载时出现错误,则最多重试 5 次。我希望它在完成下载后用它们的变量调用不同的回调。
这是我写的:
private void Download(string url, (something) callback)
{
if (asyncworkers++ < Global.paralleldownloads -1) // async download
{
using (WebClient client = new WebClient())
{
client.Proxy = (Global.proxymode == 2 ? new WebProxy(dynamicproxy) : (Global.proxymode == 1 ? new WebProxy(Global.proxy) : null));
System.Timers.Timer timer = new System.Timers.Timer(5000);
timer.Enabled = true;
client.DownloadStringCompleted += (sender, e) =>
{
asyncworkers--;
if (timer.Enabled)
{
timer.Stop();
if (e.Error == null && e.Result.Length > 0)
{
AppendTextBox("successful async\r\n");
errors = 0;
//call "callback" and its variables here
}else{
AppendTextBox("empty async\r\n");
if (errors++ > 3)
{
//stop trying
}else{
Download(url, callback);
}
}
}
};
client.DownloadStringAsync(new Uri(url));
timer.Elapsed += (sender, e) =>
{
AppendTextBox("timeout async\r\n");
timer.Enabled = false;
client.CancelAsync();
Download(url, callback);
};
}
}else{ // sync download to delay it
var request = WebRequest.Create(url);
request.Proxy = (Global.proxymode == 2 ? new WebProxy(dynamicproxy) : (Global.proxymode == 1 ? new WebProxy(Global.proxy) : null));
request.Timeout = 5000;
using (var response = request.GetResponse())
{
using (var stream = response.GetResponseStream())
{
using (var reader = new StreamReader(stream))
{
string data = reader.ReadToEnd();
if (data.Length > 0)
{
AppendTextBox("successful sync\r\n");
asyncworkers--;
errors = 0;
//call "callback" and its variables here
return;
}
}
}
}
asyncworkers--;
AppendTextBox("error sync\r\n");
if (errors++ > 3)
{
//stop trying
}else{
Download(url, callback);
}
}
}
这就是我想使用它的方式:
Download("http://.....", GetDataDone(var1, var2, var3, var4));
或者
Download("http://.....", UpdateDone());
我希望我所描述的对你来说至少有点清楚。我怎样才能让它按我希望的方式工作?谢谢!