C# 在线程中执行方法时。它是否也调用(默认/参数化)构造函数
在线程中执行方法时。在调用方法之前,它是否还会调用包含该方法的类的(默认/参数化)构造函数C# 在线程中执行方法时。它是否也调用(默认/参数化)构造函数,c#,threadpool,C#,Threadpool,在线程中执行方法时。在调用方法之前,它是否还会调用包含该方法的类的(默认/参数化)构造函数 public class Class1 { HttpContext h = null; public Class1(HttpContext _h) { h = _h; } public Class1() { if (h != null) { HttpContext.Current = h
public class Class1
{
HttpContext h = null;
public Class1(HttpContext _h)
{
h = _h;
}
public Class1()
{
if (h != null)
{
HttpContext.Current = h;
}
}
ManualResetEvent[] wsManualResetEvents = new ManualResetEvent[1];
public void callThread()
{
HttpContext.Current.Session["ok"] = "ll";
wsManualResetEvents[0] = new ManualResetEvent(false);
ThreadPool.QueueUserWorkItem(new WaitCallback(o => me()));
if (wsManualResetEvents != null && wsManualResetEvents[0] != null)
{
WaitHandle.WaitAll(wsManualResetEvents);
}
}
private void me()
{
var d = HttpContext.Current.Session["ok"].ToString();
wsManualResetEvents[0].set();
}
}
我试图做的是将线程的httpcontext设置为与正在执行的线程等效。否,启动线程不会调用构造函数。对于您的代码,您有一个
Class1
实例,您正在对其调用.callThread()
。在后台线程上调用me()
时,它在Class1
的同一实例上调用me()
。仅仅因为你启动了一个新线程并不意味着你已经创建了一个新的Class1
对象。我们在会话中有很多东西,线程经常操纵会话变量。因此,我们最终将httpcontext作为参数传递给thread方法,并设置httpcontext.current=http_context_from_参数。