我编写了一个小程序来探索将 Berkeley DB 与 C# 结合使用。
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using BerkeleyDB;
namespace bdbtest {
class Program {
const string dbfile = @"c:\tmp\test.db";
const int nIndexes = 5, nRecords = 500;
static SecondaryKeyGenDelegate MakeKeyGen(int idx) {
return (k, v) => new DatabaseEntry(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(v.Data) + string.Format("_{0}", idx)));
}
static void Main(string[] args) {
File.Delete(dbfile);
var environment = DatabaseEnvironment.Open(null,
new DatabaseEnvironmentConfig() {
Create = true,
Private = true,
UseMPool = true,
ErrorPrefix = "Env: ",
ErrorFeedback = (pfx, msg) => Console.WriteLine(pfx + msg),
});
var table = RecnoDatabase.Open(dbfile, "table",
new RecnoDatabaseConfig() {
Env = environment,
Creation = CreatePolicy.IF_NEEDED,
ErrorPrefix = "Table: ",
ErrorFeedback = (pfx, msg) => Console.WriteLine(pfx + msg),
});
var indexes = new List<SecondaryBTreeDatabase>();
for (int idx = 0; idx < nIndexes; ++idx)
indexes.Add(SecondaryBTreeDatabase.Open(dbfile, string.Format("index_{0}", idx),
new SecondaryBTreeDatabaseConfig(table, MakeKeyGen(idx)) {
Env = environment,
Creation = CreatePolicy.IF_NEEDED,
Compare = (k1, k2) => string.Compare(Encoding.UTF8.GetString(k1.Data), Encoding.UTF8.GetString(k2.Data)),
ErrorPrefix = "Index: ",
ErrorFeedback = (pfx, msg) => Console.WriteLine(pfx + msg),
}));
for (int rn = 0; rn < nRecords; ++rn) {
string s = string.Format("rec{0}", rn);
table.Append(new DatabaseEntry(Encoding.UTF8.GetBytes(s)));
Console.WriteLine(s);
}
foreach (var index in indexes)
index.Close();
indexes.Clear();
table.Close();
environment.Close();
}
}
}
它创建一个用作表的数据库和许多辅助数据库作为该表的索引。问题是崩溃并出现以下错误:
未处理的异常:System.AccessViolationException:试图读取或写入受保护的内存。这通常表明其他内存已损坏。 在 BerkeleyDB.Internal.libdb_csharpPINVOKE.DB_put(HandleRef jarg1,HandleRef jarg2,HandleRef jarg3,HandleRef jarg4,UInt32 jarg5) 在 BerkeleyDB.Internal.DB.put(DB_TXN txn,DatabaseEntry 键,DatabaseEntry 数据,UInt32 标志) 在 BerkeleyDB.Database.Put(DatabaseEntry 键,DatabaseEntry 数据,Transaction txn,UInt32 标志) 在 BerkeleyDB.RecnoDatabase.Append(DatabaseEntry 数据,交易 txn) 在 BerkeleyDB.RecnoDatabase.Append(DatabaseEntry 数据) 在 C:\Users\fgb\Documents\Visual Studio 2008\Projects\bdbtest\bdbtest\Program.cs:line 53 中的 bdbtest.Program.Main(String[] args)
在将一定数量的记录写入表后,它总是崩溃。此外,当我增加 nIndexes 的值时,在崩溃之前写入的记录数会下降。如果这些值足够低(例如 nIndexes = 5,nRecords = 50),则程序将顺利完成。这让我觉得我正在用完有限的资源,但我就是看不出问题出在哪里。