为什么在新线程中调用此代码不起作用?
上返回的错误为Object reference not set to an instance of an object.
return pb.GetPropertyValue("Name").ToString();
这是有效的
GetFullName(m);
虽然这不是
Thread t = new Thread(GetFullName);
t.IsBackground = true;
t.Start();
public string GetFullName(string username)
{
ProfileBase pb = ProfileBase.Create(username);
return pb.GetPropertyValue("Name").ToString();
}
答案 0 :(得分:1)
也许这是因为HttpContext.Current在新线程中不可用(这是预期的)。
我建议您在“主线程”(提供请求的主线程)上提取必要的数据,然后手动将其传递给新线程。
编辑:如果你想传输HttpContext,它的工作原理如下:
HttpContext ctx = HttpContext.Current;
Thread t = new Thread((string username) => {
HttpContext.Current = ctx;
GetFullName(userName);
});
t.IsBackground = true;
t.Start();
public string GetFullName(string username)
{
ProfileBase pb = ProfileBase.Create(username);
return pb.GetPropertyValue("Name").ToString();
}