Let’s say I have the following code within another method:
Parallel.For(0, pageCount,
page =>
{
var request = (HttpWebRequest)WebRequest.Create(
string.Format(url,
selectedRegion["id"].InnerText, page));
request.BeginGetResponse(
new AsyncCallback(FinishRequestRegion), request);
});
And this is the callback for the expected response:
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;
}
}
I’m getting an error when 2 responses are trying to write to the file at the same time (classic message “another process is accessing the file”).
How can I do to make the concurrent processes to wait for the file to be unlocked so it can then record the desired information there?
You need to lock something: