Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are static methods in ASP.NET code-behind classes non-thread-safe?

Can I use static methods in my ASP.NET Pages and UserControls classes if they don't use any instance members? I.e.:

protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gridStatement.DataSource = CreateDataSource();
    gridStatement.PageIndex = e.NewPageIndex;
    gridStatement.DataBind();
}

private static DataTable CreateDataSource()
{
    using (var command = new SqlCommand("SELECT foobar"))
    {
        var table = new DataTable();
        new SqlDataAdapter(command).Fill(table);
        return table;
    }
}

Or this is not thread-safe?

like image 937
abatishchev Avatar asked Dec 08 '09 11:12

abatishchev


People also ask

Is static class thread safe?

This can be a little bit confusing, but as it turns out, the static properties on a static class are not thread safe. What this means is that the property is shared between threads.

Are static methods thread safe C#?

Static methods are not inherently thread-safe. CLR of C# doesn't thread different than instance method.

Is it OK to use static methods?

Since static methods cannot reference instance member variables, they are a good choice for methods that don't require any object state manipulation. When we use static methods for operations where the state is not managed, then method calling is more practical.

Why You Should Avoid static classes?

Static classes have several limitations compared to non-static ones: A static class cannot be inherited from another class. A static class cannot be a base class for another static or non-static class. Static classes do not support virtual methods.


1 Answers

Yes, you can use static methods - they are thread-safe. Each thread will execute in a separate context and therefore any objects created inside a static method will only belong to that thread.

You only need to worry if a static method is accessing a static field, such as a list. But in your example the code is definitely thread-safe.

like image 169
Jaco Pretorius Avatar answered Sep 18 '22 22:09

Jaco Pretorius