2
\$\begingroup\$

Please help me decide whether this should be good or bad idea to declare a Singleton variable in Global.asax file. (It is not actually singleton pattern, I just want to make sure that only one instance is created for this class.)

public class Global : System.Web.HttpApplication
{
    private HTML5Video dailyHtml5Video;

    public HTML5Video DailyHtml5Video
    {
        get
        {
            if (dailyHtml5Video==null)
            {
                dailyHtml5Video = new HTML5Video();
            }

            return dailyHtml5Video;
        }
    }

}

Will this cause any thread-related issues or other possible issues?

\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

It is not thread safe. You can use Lazy type to create a variable of HTML5Video in a thread safe manner.

Lazy<HTML5Video> dailyHtml5Video = new Lazy<HTML5Video>(() => new HTML5Video());
public HTML5Video DailyHtml5Video
{
    get {return dailyHtml5Video.Value;}
}

You can read about different versions of Singleton pattern here http://csharpindepth.com/articles/general/singleton.aspx

\$\endgroup\$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.