0

I've defined a customized HttpHandler to run my own web applications like this:

public interface IMyApp {
    public void InitOnce();
    public void Run();
}

public class MyApp1 : IMyApp {
    public void InitOnce() {
        // heavy-load some data on initializing
    }

    public void Run() {
    }
}

//
// and there are MyApp2, MyApp3 .... MyAppN both implement IMyApp interface
//

public class MyHttpHandler : IHttpHandler, IRequiresSessionState {
    public bool IsReusable { get; } = false;

    public virtual void ProcessRequest(HttpContext ctx) {
        var appID = ctx.Request.Params["appID"];
        // create a fresh app instance depend on user request.
        var app = (IMyApp)AppUtil.CreateInstance(appID);

        /*
         * TODO: I want some magics to make this method run only once.
         */
        app.InitOnce(); 

        app.Run();
    }
}

As MyAppX instance will be created dynamically many times, I want to ensure that InitOnce() can only be processed once when MyApp1,2,3..N created at very first time. (just like putting InitOnce() in each of their static constructor)

Are there any talent ideas to do this? (try to avoid heavy locks if you can please)

ineztia
  • 815
  • 1
  • 13
  • 29
  • The other instances will have to wait until initialization is complete, so what can you do other than `lock`ing inside `InitOnce`? Or maybe a [singleton](http://stackoverflow.com/a/1131826/11683) would suit you better. – GSerg Mar 28 '16 at 10:21
  • thx and "Lock" will work as expected in this case, either inside or outside InitOnce(). However I'd like to know what kind of lock do you prefer ? I just want to maximum the performence and try to avoid waiting "heavy lock-acquire-release" actions on every request. @GSerg – ineztia Mar 29 '16 at 13:55
  • I meant the `lock` keyword. For its performance, see e.g. http://stackoverflow.com/q/4673618/11683 – GSerg Mar 29 '16 at 16:05

1 Answers1

0

Just put the app Id into a static private dictionary and check it before the code block. Check Dictionary is thread safe, otherwise just put a lock around checking the dictionary.

Daniel van Heerden
  • 836
  • 1
  • 7
  • 25
  • That's the way I've tried. It means I have to lock the dictionary on some level in order to make "appID-check-modify" action to be thread-safe, right ? @Daniel van Heerden – ineztia Mar 29 '16 at 13:44
  • I'd just simply put a lock around the dictionary check and the insert. Don't mess with it. Something like `lock(locker) { if (_mydictionary.ContainsKey(appid) return; _mydictionary.Add(appid,null); }` don't think you need to get more complicated that that. – Daniel van Heerden Mar 30 '16 at 06:59