我有一个程序,我需要在外部sharepoint站点创建一些大量的文件夹(外部意思是我不能使用sharepoint对象模型).Web请求适用于此,但只需一次执行一个(发送请求,等待响应,重复)相当慢.我决定多线程化请求,尝试加快速度.该程序已大大加快,但经过一段时间(1-2分钟左右)后,并发异常开始被抛出.
代码在下面,这是最好的方法吗?
Semaphore Lock = new Semaphore(10, 10);
List<string> folderPathList = new List<string>();
//folderPathList populated
foreach (string folderPath in folderPathList)
{
Lock.WaitOne();
new Thread(delegate()
{
WebRequest request = WebRequest.Create(folderPath);
request.Credentials = DefaultCredentials;
request.Method = "MKCOL";
WebResponse response = request.GetResponse();
response.Close();
Lock.Release();
}).Start();
}
for(int i = 1;i <= 10;i++)
{
Lock.WaitOne();
}
Run Code Online (Sandbox Code Playgroud)
例外情况是这样的
未处理的异常:System.Net.WebException:无法连接到远程服务器---> System.Net.Sockets.SocketException:System.Net.Sockets通常只允许192.0.0.1:81使用每个套接字地址的一个用法
.
System.Net.SService.ConnectSocketInternal上的System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP)
中的Socket.DoConnect(EndPoint endPointSnapshot,SocketAddre ss socketAddress)(布尔值connectFailure,套接字s4,套接字s6,套接字和套接字,IPAddress和地址,ConnectSocketState state,IAsyncResult asyncResult,Int32 timeout,Exception&exception)