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?
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.
Static methods are not inherently thread-safe. CLR of C# doesn't thread different than instance method.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With