使方法在多线程http会话中只运行一次



我定义了一个自定义的HttpHandler来运行我自己的web应用程序,如下所示:

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();
    }
}

由于MyAppX实例将被动态创建多次,我想确保在第一次创建MyApp1,2,3.N时,InitOnce()只能处理一次。(就像在每个静态构造函数中放入InitOnce()一样)

有什么天才的想法可以做到这一点吗?(如果可以的话,尽量避免重锁)

只需将应用程序Id放入一个静态专用字典中,并在代码块之前进行检查。Check Dictionary是线程安全的,否则只需锁定检查字典即可。

最新更新