views:

77

answers:

1

I've a legacy application using Asp.Net WebSite (winforms...) and I need run a background thread that collect periodically some files. But this thread must run just one time!

My problem start when I put a method in Application_Start:

void Application_Start(object sender, EventArgs e) {
    SetConnection();
    SetNHibernate();
    SetNinject();
    SetExportThread();
}

So I start my application on Visual Studio and three threads start to run.

I need some singleton? or something?

A: 

Try creating a static method and variable:

private static bool _inited = false;
private static object _locker = new object();
private static void Init()
{        
    if (!_inited)
    {
        lock(_locker)
        {
            // Have to check again because the first check wasn't thread safe
            if (!_inited)
            {
                SetConnection();
                SetNHibernate();
                SetNinject();
                SetExportThread();
                _inited = true;
            }
        }
    }
}

void Application_Start(object sender, EventArgs e)
{
    Init();
}
Caleb