如何避免在 ASP.NET 中重复调用初始化方法?
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) { // sadly, **never** in here }
MyInit() // Slow initialization method, that I only wan't to call one time.
}
因此,如果我无法将 MyInit()
塞入 if
中,我可以使用 OnNeedDataSource()
解决我的性能/结构问题吗>?
protected void Page_Load(object sender, EventArgs e) {
if (!IsPostBack) { // sadly, **never** in here }
MyInit() // Slow initialization method, that I only wan't to call one time.
}
So, if I can't tuck my MyInit()
in the if
, can I solve my performance/strucktur problem with use of OnNeedDataSource()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不太确定这是否是您的意思,但是要从 Page_Load 初始化某些内容,您可以使用带有静态 bool 的静态类来确定它是否已初始化。鉴于它位于 Page_Load 上,您还需要防止多个线程 - 因此使用双重检查锁来使其线程安全并防止竞争条件。
并在您的 Page_Load 中,通过
InitMe.MyInit()
调用它希望有帮助。
Not really sure if this is what you mean, but to initialise something once from Page_Load, you could use a static class with a static bool to determine if it's been initialized. Given it's on Page_Load, you'll also need to guard against multiple threads - so use a double checked lock to make it threadsafe and guard against a race condition.
and in your Page_Load, call it via
InitMe.MyInit()
Hope that helps.
试试这个:
我假设您位于页面或用户控件中......
HTH。
Try this:
I assume you are in a page or user control...
HTH.