Windows phone中的循环异步请求网络时的线程问题
最近遇到这样一个问题,主体代码如下。目的是遍历一个list,从中取出id,然后用这个id去请求网络,得到返回数据并保存至数据库。但因为ResponseCallback是一个异步的过程,所以一直会产生这样一个异常:InvalidOperationException “The operation cannot be performed because an operation on another thread has not been completed.”
这种问题应该很常见,求指点。
代码:
foreach (var item in list)
{
GetResult(item.id);
}
void GetResult(string id)
{
string url = "http://xxxx" + id;
HttpWebRequest request = WebRequest.CreateHttp(new Uri(url));
request.BeginGetResponse(ResponseCallback, request);
}
private void ResponseCallback(IAsyncResult ar)
{
//将请求得到的数据保存至数据库中
}
偶百度了下,你这个问题是ResponseCallback里面几个线程同时访问了数据库导致了异常,HttpWebRequest虽然只有异步方式,但是可以用AutoResetEvent模拟出同步的方式,参考这货的例子http://www.silverlightchina.net/html/zhuantixilie/winphone7/2012/0906/18689.html
可以让这些请求一个一个执行。
然后我记得,多个线程访问同一个代码段的时候,可以用lock什么的锁住,同一个对象可以用Monitor锁住,这是另一种思路,你可以试试看看