동일한 데이터베이스 구조의 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.
나는이 문제를 어떻게 처리 할 수있는 어떤 아이디어?
가 기록 된 방법, 당신의 대량 복사에 의존하고 그것을 작동하는 방법. 현재 연결이 지속되면 차단할 수 있습니다. – Hey24sheep