views:

246

answers:

2

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?

+2  A: 

nothing shared across threads, so it is thread safe. unless you access static members that other static methods have a chance of executing concurrently with it...

cruizer
+4  A: 

Yes, you can use static members - 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.

Jaco Pretorius