我在C#中使用WebClient类,4.0。我需要用30,000个不同的ID打一个REST服务,并获取状态结果(200或404)。下面是进行调用的方法(eventCounter是CountdownEvent对象):等待所有异步WebClient调用完成
private void doWork()
{
initDB();
List<string> _lines = new List<string>();
//pull all UpcIds into a List
using (StreamReader _rdr = new StreamReader(@"C:\Users\kkohut\Dropbox\ROVI\Application Support\BestBuy\upc_test2.txt"))
{
string _line;
while ((_line = _rdr.ReadLine()) != null)
{
_lines.Add(_line);
}
}
numIds = _lines.Count();
for (int i = 0; i < numIds; i++)
{
string _upcId = _lines[i];
WebClient c = new WebClient();
c.DownloadDataCompleted += new DownloadDataCompletedEventHandler(c_DownloadDataCompleted);
c.DownloadDataAsync(new Uri(BASE_URL + _upcId), _upcId);
}
//this is not working correctly. Code execution hits this line and waits, without processing any of the
//the DownloadDataCompleted eventhandlers
eventCounter.Wait();
}
这里是DownloadDataCompleted事件处理
void c_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
DataSet _ds = new DataSet();
string _upcId = e.UserState.ToString();
string _status = "404";
try
{
if (!e.Cancelled && e.Error == null)
{
string _result = System.Text.Encoding.UTF8.GetString(e.Result);
if (_result.IndexOf("<code>200</code>") > 0)
{
_status = "200";
}
}
}
catch (Exception ex)
{
_status = "404";
}
finally
{
updateDB(_upcId, _status);
eventCounter.Signal(1);
txtLog.Text += string.Format("{0}\t{1}\t{2}\r\n",ctr, _upcId, _status);
}
}
如果我注释掉eventCounter.Wait()语句,调用工作,但我无法知道他们何时完成。这是一个winforms应用程序,所以只要我保持表单运行,所有的调用完成。但是,如果我取消注释eventCounter.Wait()语句,则不会处理任何调用。看起来,Wait()语句阻止了开始的异步调用。我找到的每个例子都使用这种方法,但是他们都没有在完成的事件处理程序中发出CountdownEvent信号。思考?
@Aliostad - 后说,这是一个CountdownEvent对象(http://msdn.microsoft.com/en-us/library/system.threading.countdownevent.aspx),但是初始化不显示 - 也许这就是问题? – 2012-03-09 16:47:56
@SteveHaigh感谢.........我错过了 – Aliostad 2012-03-09 16:52:48
我实例倒数opject,在列表中 – 2012-03-09 17:27:45