为什么Lucene.Net索引器抛出System.IO.IOException未处理?

Kum*_*mar 6 .net c# lucene lucene.net visual-studio-2010

有时会抛出异常,说该文件write.lock无法被其他进程使用,但是这是一个非常简单的Lucene.Net测试应用程序,并且没有其他进程使用它,任何关于如何使用它的想法

例外情况如下:

System.IO.IOException was unhandled
HResult=-2147024864
Message=The process cannot access the file 
     'c:\temp\luceneidx\write.lock' because it is being used by another process.

Source=mscorlib
StackTrace:
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
    at System.IO.File.InternalDelete(String path, Boolean checkHost)
    at System.IO.File.Delete(String path)
    at Lucene.Test.LuceneSearchInternal.get__directory() 
    in C:\Lucene.Test\LuceneSearchResumes.cs:line 35
Run Code Online (Sandbox Code Playgroud)

抛出异常的相关代码是,

var lockFilePath = Path.Combine(_luceneDir, "write.lock");

if (File.Exists(lockFilePath))
    File.Delete(lockFilePath);   // THROWS exception sometimes
Run Code Online (Sandbox Code Playgroud)

代码主要来自本文.

索引是在后台线程上构建的Task.Factory.StartNew(),WPF GUI在构建索引时进行搜索.只有一个线程将文档写入索引.

问题:哪个其他进程正在使用Lucene.Net索引?

rae*_*ae1 3

假设所提供的代码与搜索过程(而不是索引过程)相关,那么您不应该在每次尝试访问索引时都尝试删除锁定文件。抛出异常是因为后台线程当前正在写入索引,并且当线程本身应该处理删除时,您任意尝试删除其锁定文件。

在您发布的文章中,此机制用于在写入索引时发生系统/应用程序崩溃后恢复Lucene 索引,使其处于锁定状态。然而,这并不常见。我相信在 CodeProject 文章中假设对索引的单线程访问,因此采用了这种方法。

在您的项目中,您需要能够检查锁定文件的存在是由于当前的写访问还是由于先前的应用程序/系统崩溃。您可以lock在代码中使用一个在崩溃时动态释放的对象来区分这两种情况。