1

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

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 请求线程运行时,相同的代码运行良好。是否有可能让这个东西在后台线程本身工作?如果是怎么办?

谢谢,普拉丹

4

1 回答 1

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 项目来执行此操作,该库旨在与 Web 服务一起使用,但没有理由不能直接调用这些方法来呈现控件。

于 2013-01-08T13:28:19.353 回答