假设我在另一个方法中有以下代码:
Parallel.For(0, pageCount,
page =>
{
var request = (HttpWebRequest)WebRequest.Create(
string.Format(url,
selectedRegion["id"].InnerText, page));
request.BeginGetResponse(
new AsyncCallback(FinishRequestRegion), request);
});
这是预期响应的回调:
void FinishRequestRegion(IAsyncResult res)
{
try
{
var response = (res.AsyncState as HttpWebRequest).EndGetResponse(res) as HttpWebResponse;
var docCitizens = new XmlDataDocument();
var readerCitizens = new XmlTextReader(response.GetResponseStream());
readerCitizens.MoveToContent();
docCitizens.Load(readerCitizens);
readerCitizens.Close();
if (docCitizens["error"]!=null)
return;
var selectedRegion = docCitizens["region"];
var regionCitizens = selectedRegion["citizens"];
var result = (regionCitizens.Cast<XmlNode>().Select(citizen => citizen["id"].InnerText)).ToList();
File.AppendAllLines("list.txt", result);
}
catch (Exception ex)
{
return;
}
}
当 2 个响应尝试同时写入文件时出现错误(经典消息“另一个进程正在访问文件”)。如何使并发进程等待文件被解锁,以便它可以在那里记录所需的信息?