[英]How to force HttpModule Init() method call for all new thread
我沒有開發asp.net應用程序的經驗。
我想開發一個Web應用程序,該應用程序使用免注冊SxS的Componente COM。
在這篇MSDN文章之后,Http模塊我實現了一個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應用程序,並且可以成功調用componente COM,但只能用於運行HttpModule Init的同一線程。
如果我單擊按鈕再次運行,則使用COM的線程會更改並失敗,因為未調用HttpModule Init()。
如何檢測到所有新線程來正確調用Init()和CreateActCtx? 可能嗎?
考慮像這樣使用裝飾有[ThreadStatic]屬性的布爾值標志。
[ThreadStatic]
static bool _hasInitBeenCalled;
在每個事件上,檢查該標志是否為真。 如果不是,請運行您的初始化代碼,然后將標志設置為true。 本質上,該變量對於每個線程都是唯一的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.