【发布时间】:2012-02-22 04:58:53
【问题描述】:
我有一个应用程序可以爬取网站并将内容作为 lucene 索引文件写入物理目录。
当我为此目的使用线程时,由于锁定,我会遇到写入错误或错误。
我想使用多个线程并写入索引文件而不会丢失任何线程的任务。
public class WriteDocument
{
private static Analyzer _analyzer;
private static IndexWriter indexWriter;
private static string Host;
public WriteDocument(string _Host)
{
Host = _Host;
Lucene.Net.Store.Directory _directory = FSDirectory.GetDirectory(Host, false);
_analyzer = new StandardAnalyzer();
bool indexExists = IndexReader.IndexExists(_directory);
bool createIndex = !indexExists;
indexWriter = new IndexWriter(_directory, _analyzer, true);
}
public void AddDocument(object obj)
{
DocumentSettings doc = (DocumentSettings)obj;
Field urlField = new Field("Url", doc.downloadedDocument.Uri.ToString(), Field.Store.YES, Field.Index.TOKENIZED);
document.Add(urlField);
indexWriter.AddDocument(document);
document = null;
doc.downloadedDocument = null;
indexWriter.Optimize();
indexWriter.Close();
}
}
对于上面的类,我传递的值是这样的:
DocumentSettings writedoc = new DocumentSettings()
{
Host = Host,
downloadedDocument = downloadDocument
};
Thread t = new Thread(() =>
{
doc.AddDocument(writedoc);
});
t.Start();
如果我在t.Start(); 之后添加t.Join();,则代码对我有效,没有任何错误。但这会减慢我的进程,实际上,这等于我在不使用线程的情况下得到的输出。
我收到如下错误:
Cannot rename /indexes/Segments.new to /indexes/Segments
the file is used by some other process.
谁能帮我解决这个代码?
【问题讨论】:
-
您遇到什么错误?我们可以看看你正在使用的代码的一个小例子吗?
标签: c# multithreading thread-safety threadpool web-crawler