如果他们不使用任何实例成员,我可以在我的ASP.NET static
和Pages
类中使用UserControls
方法吗?即:
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;
}
}
或者这不是线程安全的吗?
答案 0 :(得分:8)
是的,您可以使用静态成员 - 它们是线程安全的。每个线程都将在一个单独的上下文中执行,因此在静态方法中创建的任何对象都只属于该线程。
如果静态方法正在访问静态字段(例如列表),则只需要担心。但在您的示例中,代码绝对是线程安全的。
答案 1 :(得分:2)
没有在线程之间共享,因此它是线程安全的。除非你访问静态成员,否则其他静态方法有可能与它同时执行......
答案 2 :(得分:1)
public class RaceConditionSample
{
private static int number = 0;
public static int Addition()
{
int x = RaceConditionSample.number;
x = x + 1;
RaceConditionSample.number = x;
return RaceConditionSample.number;
}
public int Set()
{
RaceConditionSample.number = 42;
return RaceConditionSample.number;
}
public int Reset()
{
RaceConditionSample.number = 0;
return RaceConditionSample.number;
}
}
RaceConditionSample sample = new RaceConditionSample();
System.Diagostics.Debug.WriteLine(sample.Set());
// Consider the following two lines are called in different threads in any order, Waht will be the
// output in either order and/or with any "interweaving" of the individual instructions...?
System.Diagostics.Debug.WriteLine(RaceConditionSample.Addition());
System.Diagostics.Debug.WriteLine(sample.Reset());
答案是:它可能是“42,43,0”,“42,0,1”,你以前不知道......