首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Npgsql - BulkCopy来自ConcurrentQueue<T>

Npgsql - BulkCopy来自ConcurrentQueue<T>
EN

Stack Overflow用户
提问于 2017-05-11 08:30:22
回答 1查看 203关注 0票数 0

假设我有这样的方法:

代码语言:javascript
复制
public async Task BulkCopy(ConcurrentQueue<Model> modelQueue, string connectionString)
{
    while(modelQueue.IsEmpty == false)
    {
        try
        {
            using(NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                await connection.OpenAsync();

                using(var writer = connection.BeginBinaryImport("COPY myTable (Id,Name,Something,SomethingElse)"))
                {
                    // Is this what I'm supposed to do?
                    foreach(Model item in modelQueue)
                    {
                        writer.WriteRow(item);
                    }
                }
            }
        }
    }
}

模型具有Guid、string名称、string string、string SomethingElse(就像表一样)的属性。

我可以使用WriteRow()并传入整个对象吗?这是实现的方式,还是我做错了?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-12 10:31:16

这个问题的答案非常简单,因为ConcurrentQueue实现了IEnumerable,我所要做的就是在队列中运行并写入数据。

代码语言:javascript
复制
public async Task BulkCopy(ConcurrentQueue<Model> modelQueue, string connectionString)
{
    while(modelQueue.IsEmpty == false)
    {
        try
        {
            using(NpgsqlConnection connection = new NpgsqlConnection(connectionString))
            {
                await connection.OpenAsync();

                using(var writer = connection.BeginBinaryImport("COPY myTable (Id,Name,Something,SomethingElse) FROM STDIN (FORMAT BINARY)"))
                {
                    foreach(Model item in modelQueue)
                    {
                        writer.StartRow();
                        writer.Write(item.Id, NpgsqlTypes.NpgsqlDbType.Uuid);
                        writer.Write(item.Name);
                        writer.Write(item.Something);
                        writer.Write(item.SomethingElse);
                    }
                }
            }
        }
    }
}

这似乎能胜任这项工作。30000张唱片所需的时间平均为540毫秒。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43910314

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档