如何强制所有新线程调用HttpModule Init()方法
本文关键字:调用 HttpModule 方法 Init 线程 何强制 新线程 | 更新日期: 2023-09-27 17:58:50
我没有开发asp.net应用程序的经验。
我想开发一个使用SxS免费注册的组件COM的web应用程序。
在这篇MSDN文章之后,HttpModule I实现了一个HttpModule
public class SyncModule : IHttpModule
{
private MyEventHandler _eventHandler = null;
public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(OnBeginRequest);
// Code that enable COM SxS registration-free
EnableSxSForThisThread_with_CreateActCtx();
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
Debug.WriteLine("MyModule Thread Id: " + id);
}
public void Dispose() { }
public delegate void MyEventHandler(Object s, EventArgs e);
public event MyEventHandler MyEvent
{
add { _eventHandler += value; }
remove { _eventHandler -= value; }
}
public void OnBeginRequest(Object s, EventArgs e)
{
HttpApplication app = s as HttpApplication;
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
Debug.WriteLine("OnBeginRequest Thread Id: " + id);
Debug.WriteLine("OnBeginRequest: Hello from OnBeginRequest in custom module.<br>");
if (_eventHandler != null)
_eventHandler(this, null);
}
请注意,打印线程ID。
public void Init(HttpApplication app)
{
...
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
Debug.WriteLine("MyModule Thread Id: " + id);
}
我链接了我的web应用程序,把它放在"web.confg"中
<httpModules>
<add name="MyModule" type="MyModule.SyncModule, MyModule" />
</httpModules>
我运行我的web应用程序,可以成功地调用组件COM,但只能用于运行HttpModule Init的同一线程。
如果我单击按钮再次运行使用COM更改的线程,并且由于未调用HttpModule Init()而失败。
如何检测所有新线程以正确调用Init()和CreateActCtx有可能吗?
考虑使用用[ThreadStatic]属性装饰的布尔标志,如下所示。
[ThreadStatic]
static bool _hasInitBeenCalled;
在每个事件中,检查该标志是否为真。如果不是,请运行init代码,然后将标志设置为true。本质上,变量对于每个线程都是唯一的。