同じデータベース構造の59台のサーバーに接続し、同じテーブルにローカルデータベースにデータをインポートする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