繁体   English   中英

使用 Dapper 和 SQLite,Query Method 抛出空引用异常

[英]Using Dapper with SQLite, Query Method throws a null reference exception

测试环境:

-- 框架版本:.NET 6

-- Microsoft.Data.Sqlite,版本:6.0.6

-- Dapper,版本:2.0.123

问:只执行一个查询时,没有问题。 执行多个并发查询时会出现问题。

(参考:当我用原生ADO.NET而不是Dapper(conn.Query)写代码时,没有问题!)

这是一个简单的演示,可以很容易地重现问题。

using System.Data;
using Dapper;
using Microsoft.Data.Sqlite;

// SQLite db file
string connStr = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}test.db";

// SQLite connection (Share the singleton connection) 
using SqliteConnection conn = new SqliteConnection(connStr);
conn.Open();
 
bool existError = false;
while (true)
{
    if (existError == true)
    {
        break;
    }

    // Perform concurrent reads
    Parallel.For(0, 100, index =>
    {
        try
        {
            // Test SQL
            string sql_test = " select * from T_Account where AccountId='ab001' ";

            // Perform query data (May throw a null reference exception )
            var t = conn.Query(sql_test);
        }
        catch (Exception ex)
        {
            existError = true;

            // Test output: Object reference not set to an instance of an object.
            Console.WriteLine($"Read error ({index}): {ex.Message}");
        }
    });

    Console.WriteLine($"{DateTime.Now}-------- split line --------");
}

整个项目一直在用Dapper,想知道问题出在哪里,应该怎么解决?

您可能认为重用连接是一个非常好的主意,但事实并非如此。 ADO 已经内置了一个连接池,它比我们能想出的任何东西都高效得多。 我尝试运行您的代码,显然使用另一个 sqlite 数据库和查询,并且在第 6 次或第 7 次迭代中,我得到了空引用异常。 然后我像这样更改了您的代码:

// Perform concurrent reads
Parallel.For(0, 100, index =>
{
    try
    {
        // These two lines moved inside the loop
        using SqliteConnection conn = new SqliteConnection(connStr);
        conn.Open();

        // Test SQL
        string sql_test = " select * from T_Account where AccountId='ab001' ";

        // Perform query data (May throw a null reference exception )
        var t = conn.Query(sql_test);
    }
    catch (Exception ex)
    {
        existError = true;

        // Test output: Object reference not set to an instance of an object.
        Console.WriteLine($"Read error ({index}): {ex.Message}");
    }
});

并且代码可以按预期继续运行。 最佳实践是在 using 语句中创建数据库连接,并在完成后立即处理它。 由于我还没有看到您使用原始 ADO.NET 编写的代码,所以我不知道为什么会这样。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM