Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this html helper thread safe?

I am wondering if the code as referenced as the accepted answer on this link is thread safe. I mean not for multi threading. I just dont want output crossing user page requests.
Add CSS or JavaScript files to layout head from views or partial views

Would I have a situation where many requests to a page could have crossed over styles and scripts.

It may help if you have knowledge of MVC in that the add methods are called as views are rendered and the result is rendered to the layout (master page).

Current Solution (Please let me know if it should be improved)

public static MyCompanyHtmlHelpers GetInstance(HtmlHelper htmlHelper)
{
    MyCompanyHtmlHelpers _instance;
    if (htmlHelper.ViewData["SectionHelper"] == null)
    {
        _instance = new MyCompanyHtmlHelpers();
        htmlHelper.ViewData["SectionHelper"] = _instance;
    }
    else
        _instance = htmlHelper.ViewData["SectionHelper"] as MyCompanyHtmlHelpers;

    _instance.SetHtmlHelper(htmlHelper);

    return _instance;
}

thanks

like image 383
Valamas Avatar asked Jul 07 '11 11:07

Valamas


People also ask

What is thread safe in Android?

By design, Android View objects are not thread-safe. An app is expected to create, use, and destroy UI objects, all on the main thread. If you try to modify or even reference a UI object in a thread other than the main thread, the result can be exceptions, silent failures, crashes, and other undefined misbehavior.

Is HttpContext thread safe?

HttpContext access from a background threadHttpContext isn't thread-safe. Reading or writing properties of the HttpContext outside of processing a request can result in a NullReferenceException.

Are COM objects thread safe?

The object can be re-entered if one of its interface method implementations retrieves and dispatches messages or makes an ORPC call to another thread, thereby causing another call to be delivered to the object (by the same apartment). COM does not prevent re-entrancy on the same thread but it provides thread safety.

Is ASP net thread safe?

NET class libraries are not thread safe by default. Avoid providing static methods that alter static state. In common server scenarios, static state is shared across requests, which means multiple threads can execute that code at the same time.


1 Answers

Hmm.... doesn't look like it to me ;p

HtmlHelper has some instance properties, in particular ViewContext and ViewData (via ViewDataContainer) etc. Putting that anywhere static is a terrible terrible idea.

With the basic code that is going on you'll probably get away with it, but: IMO this is still a very bad idea. Well spotted.

like image 190
Marc Gravell Avatar answered Oct 01 '22 23:10

Marc Gravell