Problem using same instance of indexSearcher for m

2019-01-08 01:40发布

Am using Lucene API in a .net web application. I want to use the same instance of Indexsearcher for all the requests.Hence am storing indexsearcher instance in http cache.

here is my code for the same:

if (HttpRuntime.Cache["IndexSearcher"] == null)
                {
                    searcher = new IndexSearcher(jobIndexFolderPath);
                    HttpRuntime.Cache["IndexSearcher"] = searcher;
                }
                else
                {
                    searcher = (IndexSearcher)HttpRuntime.Cache["IndexSearcher"];
                }

When I execute the statement below, I get a runtime error :"Object reference not set to an instance of an object."

Hits hits = searcher.Search(myQuery);

What am i missing here?

Thanks for reading!

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-08 02:10

First of all it's not safe at all, it should be:

var searcher = (IndexSearcher)HttpRuntime.Cache["IndexSearcher"];
if(searcher == null)
{
     searcher = new IndexSearcher(jobIndexFolderPath);
     HttpRuntime.Cache["IndexSearcher"] = searcher;
}

In your code cache can expire between check and assignment

查看更多
登录 后发表回答