从后台线程调用时,System.Web.UI.Control.RenderControl失败

时间:2013-01-08 13:10:46

标签: c# asp.net background-thread rendercontrol

我需要在后台线程中呈现控件并以邮件方式发送输出。 所以我在后台线程中运行了这段代码:

System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(sendmail), new Object());
public void sendmail(object o)
{
    UserControl cntrl = new Page().LoadControl("~/mycontrol.ascx") as UserControl;
    StringWriter stringwriter = new StringWriter();
    Html32TextWriter htmlwriter = new Html32TextWriter(stringwriter);
    cntrl.RenderControl(htmlwriter);
    SendEmailUsingNetMail(stringwriter);
}

At runtime I am getting this exception

System.NullReferenceException: Object reference NOT SET TO an instance of an object.
AT System.Web.UI.HtmlControls.HtmlForm.GetActionAttribute()
AT System.Web.UI.HtmlControls.HtmlForm.RenderAttributes(HtmlTextWriter writer)
AT System.Web.UI.HtmlControls.HtmlControl.RenderBeginTag(HtmlTextWriter writer)
AT System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer)
AT System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output)
AT System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
AT System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
AT System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer)
AT System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
AT System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
AT System.Web.UI.Control.Render(HtmlTextWriter writer)
AT System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
AT System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
AT System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
AT RedBus.RBMail.sendmail(object o)

从asp.net请求线程运行时相同的代码完全正常。 有可能让这个东西在后台线程本身工作吗?如果是的话怎么样?

谢谢, 普拉丹

1 个答案:

答案 0 :(得分:0)

在页面中添加表单:

System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(sendmail), new Object());
public void sendmail(object o)
{

    System.Web.UI.Page() pageHolder = new System.Web.UI.Page() 
              {AppRelativeTemplateSourceDirectory = HttpRuntime.AppDomainAppVirtualPath };
    System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
    UserControl cntrl = new Page().LoadControl("~/mycontrol.ascx") as UserControl;
    form.Controls.Add(cntrl );
    pageHolder.Controls.Add(form);

    StringWriter stringwriter = new StringWriter();

    HttpContext.Current.Server.Execute(pageHolder, stringwriter, false);
    SendEmailUsingNetMail(stringwriter);
}

另外,我编写了一个名为ucajax的OSS项目,lib旨在与Web服务一起使用,但没有理由不能直接调用这些方法来呈现控件。