【发布时间】:2011-04-14 12:06:30
【问题描述】:
我需要使用 SqlBulkCopy 将大型 csv 文件分块到几个不同的数据库插入中。我打算通过 2 个单独的任务来执行此操作,1 个用于批处理 CSV 文件,另一个用于插入数据库。作为一个例子,我就是这样的:
public class UberTask
{
private readonly BlockingCollection<Tuple<string,int>> _store = new BlockingCollection<Tuple<string, int>>();
public void PerformTask()
{
var notifier = new UINotifier();
Task.Factory.StartNew(() =>
{
for (int i =0; i < 10; i++)
{
string description = string.Format("Scenario {0}", i);
notifier.PerformOnTheUIThread(() => Console.WriteLine(string.Format("Reading '{0}' from file", description)));
// represents reading the CSV file.
Thread.Sleep(500);
notifier.PerformOnTheUIThread(() => Console.WriteLine(string.Format("Enqueuing '{0}'", description)));
_store.Add(new Tuple<string, int>(description, i));
}
_store.CompleteAdding();
});
var consumer = Task.Factory.StartNew(() =>
{
foreach (var item in _store.GetConsumingEnumerable())
{
var poppedItem = item;
notifier.PerformOnTheUIThread(() => Console.WriteLine(string.Format("Sending '{0}' to the database", poppedItem.Item1)));
// represents sending stuff to the database.
Thread.Sleep(1000);
}
});
consumer.Wait();
Console.WriteLine("complete");
}
}
这是配对 2 组相关任务的好方法吗?上面的代码没有处理什么(它需要):
- 如果代表 CSV 读取的任务出现故障,则需要停止其他任务(即使 _store 中仍有项目。)
- 如果代表数据库的Task插入故障,其他进程可以停止处理。
- 如果配对任务中的任何一个出现故障,我将需要执行一些操作来回滚数据库更新(我不担心我将如何回滚),更多的问题是我如何编写“故障发生在其中一项配对任务,所以我需要整理一下”。
任何关于上述内容的帮助将不胜感激!
【问题讨论】:
标签: c# multithreading task task-parallel-library