0

I have a parallel loop generating HTML using the Parallel.ForEach statement. Somewhere in the execution i render the Html of controls using the RenderControl function. All controls render well (Textboxes, dropdownlists, checkboxes etc.) but a radiobuttonlist gives the following error:

This is the function I use to render the HTML

public static string ControlToString(Control control)
{
    var sb = new StringBuilder();
    var sw = new StringWriter(sb);
    var hw = new Html32TextWriter(sw);
    control.RenderControl(hw);
    return sb.ToString();
}

The RenderControl statement throws a null reference exception:

An exception of type 'System.NullReferenceException' occurred in System.Web.dll but was not handled in user code.Additional information: Object reference not set to an instance of an object.

If I use a normal foreach loop, the problem does not occur. This is the code I use to make the instance of the radiobuttonlist:

var listControl new RadioButtonList();
listControl.ID = "FAC_" + searchFacet.Guid;
listControl.Items.Add(new ListItem("Select an item", "-1"));

What am I doing wrong? Why is the radiobutton different from all other controls? I cheched during debugging. No parameters seem to be null.

It seems the missing HttpContext was the problem. I 'solved' it by adding a fake HttpContext:

public static string ControlToString(Control control)
{
    if (HttpContext.Current == null)
    {
        HttpContext.Current = new HttpContext(new HttpRequest(string.Empty, "http://localhost:81/default.aspx", string.Empty), new HttpResponse(null));
    }
    var sb = new StringBuilder();
    var sw = new StringWriter(sb);
    var hw = new Html32TextWriter(sw);
    control.RenderControl(hw);
    return sb.ToString();
}

It is a 'hack', does anyone have a better idea?

svick
  • 236,525
  • 50
  • 385
  • 514
Peter de Bruijn
  • 792
  • 6
  • 22
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – mybirthname Nov 21 '16 at 12:17
  • I'm throwing out a _guess_. Since it's working in a normal loop, but not with parallel, I _guess_ it's because `RenderControl` cannot render anything from a background thread. Your parellel.foreach will create another thread, in which some variable that `RenderControl` need does not exist. What happens if you set `MaxDegreeOfParallelism = 1`? [how-can-i-limit-parallel-foreach](http://stackoverflow.com/questions/9290498/how-can-i-limit-parallel-foreach) – smoksnes Nov 21 '16 at 12:32
  • My guesss would be that the httpcontext is missing. But why on earth would rendering all other controls work perfectly fine. If I use MaxDegreeOfParallelism = 1 there is no change. – Peter de Bruijn Nov 21 '16 at 12:40

0 Answers0