0

Hi I have a static class that has static variables that contain data from the database. I want these variables to be updated every 5 seconds so I created a thread, inside the same class, which will execute a function that will fetch data from the database and update the variables. But I get a nullReferenceException pointing to the line where I declare initialize my connection. Here is my code:

public static void Initialize()
    {
        if (!isInitialized)
        {
            isInitialized = true;
            Thread t = new Thread( new ThreadStart(SetProperties));
            t.Start();
        }
    }

    public static void SetProperties()
    {
        //The next line is where the NullReferenceException is pointing to
        OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + System.Web.HttpContext.Current.Server.MapPath("cms.accdb") + "';");

        using (conn)
        { ....

Any help, please? Thanks

3
  • There is no HttpContext.Current outside of the request thread. Seriously, what you're doing is silly. You need to rethink the design a lot, ASP.NET isn't really the environment for doing something like this. Commented Apr 9, 2015 at 7:28
  • @Luaan Hi. Thanks for your reply. But can u please elaborate on "There is no HttpContext.Current outside of the request thread"? And why do you think what I'm doing is silly? please guide me. I'm self-learning ASP.net. Commented Apr 9, 2015 at 7:50
  • 2
    HttpContext.Current is context-sensitive. It will only have a value on the request thread, and you left that by starting a new thread (that is, your Initialize method runs on the request thread, but SetProperties doesn't). Which causes your NullReferenceException, because you're trying to access properties of a null value. Caching is one of the hardest things in computing, so you might want to learn a bit more before attempting anything serious in that regard. Multi-threading is another of the hardest things, and here you're doing both as a beginner. Bad idea :) Commented Apr 9, 2015 at 7:57

1 Answer 1

1

In your new thread, you have no access to System.Web.HttpContext.Current object. You can replace

System.Web.HttpContext.Current.Server.MapPath("cms.accdb") 

With

HostingEnvironment.MapPath("cms.accdb") 

More info about it here: HostingEnvironment.MapPath

Sign up to request clarification or add additional context in comments.

2 Comments

@FAngle I got an error 'The relative virtual path 'cms.accdb' is not allowed here.'. any idea?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.