2017-11-14 2 views
0

동일한 데이터베이스 구조의 59 개 서버에 연결하고 데이터를 로컬 db에 동일한 테이블로 가져 오는 C# 라이브러리가 있습니다. 이 순간에 나는 foreach 루프에서 서버가 데이터 서버를 검색하고 있습니다 : 데이터를 검색 할 많은 시스템이있다Parallel.Foreach 및 BulkCopy

foreach (var systemDto in systems) 
{ 
    var sourceConnectionString = _systemService.GetConnectionStringAsync(systemDto.Ip).Result; 
    var dbConnectionFactory = new DbConnectionFactory(sourceConnectionString, 
     "System.Data.SqlClient"); 
    var dbContext = new DbContext(dbConnectionFactory); 
    var storageRepository = new StorageRepository(dbContext); 
    var usedStorage = storageRepository.GetUsedStorageForCurrentMonth(); 

    var dtUsedStorage = new DataTable(); 
    dtUsedStorage.Load(usedStorage); 
    var dcIp = new DataColumn("IP", typeof(string)) {DefaultValue = systemDto.Ip}; 
    var dcBatchDateTime = new DataColumn("BatchDateTime", typeof(string)) 
    { 
     DefaultValue = batchDateTime 
    }; 
    dtUsedStorage.Columns.Add(dcIp); 
    dtUsedStorage.Columns.Add(dcBatchDateTime); 

    using (var blkCopy = new SqlBulkCopy(destinationConnectionString)) 
    { 
     blkCopy.DestinationTableName = "dbo.tbl"; 
     blkCopy.WriteToServer(dtUsedStorage); 
    } 
} 

때문에, 나는 Pararel.Foreach 루프를 사용할 수있는 경우 궁금해? BulkCopy는 WriteToServer 동안 테이블을 잠그고 다음 WriteToServer는 이전이 완료 될 때까지 대기 할 것인가?

- EDIT 1

나는 Parallel.Foreach하는 데 Foreach을 변경했습니다하지만 한 가지 문제에 직면 해있다. 이 루프 내부에서 나는 비동기 방법이 있습니다 _systemService.GetConnectionStringAsync (systemDto.Ip) 을이 줄은 오류 반환 :

System.NotSupportedException: A second operation started on this context before a previous asynchronous operation completed. Use 'await' to ensure that any asynchronous operations have completed before calling another method on this context. Any instance members are not guaranteed to be thread safe.

나는이 문제를 어떻게 처리 할 수있는 어떤 아이디어?

+0

가 기록 된 방법, 당신의 대량 복사에 의존하고 그것을 작동하는 방법. 현재 연결이 지속되면 차단할 수 있습니다. – Hey24sheep

답변

0

일반적으로 차단되며 이전 작업이 완료 될 때까지 대기합니다.

SqlBulkCopy을 병렬로 실행할 수 있는지 여부에 영향을 줄 수있는 몇 가지 요인이 있습니다. 내 .NET Bulk OperationsParallel 기능을 추가 할 때 내가 기억

, 나는 그것을 병렬로 제대로 작동하도록 힘든 시간을 보냈습니다하지만 잘 테이블 (가능성이 결코 경우) 인덱스가 없을 때

경우에도 일 성능 향상은 훨씬 빠르지 않았습니다.

은 아마 당신은 여기에서 자세한 정보를 찾을 수 : MSDN - Importing Data in Parallel with Table Level Locking