C# ASP.NET代码隐藏类中的静态方法是非线程安全的吗?
如果ASP.NETC# ASP.NET代码隐藏类中的静态方法是非线程安全的吗?,c#,.net,asp.net,thread-safety,static-methods,C#,.net,Asp.net,Thread Safety,Static Methods,如果ASP.NET页面和用户控件类不使用任何实例成员,我可以在这些类中使用静态方法吗?即: protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) { gridStatement.DataSource = CreateDataSource(); gridStatement.PageIndex = e.NewPageIndex; gridStatement.DataB
页面
和用户控件
类不使用任何实例成员,我可以在这些类中使用静态
方法吗?即:
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;
}
}
或者这不是线程安全的?没有跨线程共享的内容,因此它是线程安全的。除非您访问静态成员,否则其他静态方法有可能与之并行执行…是的,您可以使用静态方法-它们是线程安全的。每个线程将在单独的上下文中执行,因此在静态方法中创建的任何对象都将只属于该线程
您只需要担心静态方法是否正在访问静态字段,例如列表。但在您的示例中,代码绝对是线程安全的。确实如此。在您的上下文中,关于线程安全性唯一需要担心的是涉及静态成员的概念,如前所述。 当任何方法(静态或非静态)访问静态成员时,您应该担心多线程问题。 考虑以下事项:
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”,你以前不知道。什么类型的变量是“command”对象?我认为你的评论“你可以使用静态成员”是不正确的。“成员”是字段、属性或方法。因此,根据这个定义,静态成员(变量)和静态字段是相同的。也许你的意思是说可以使用静态方法。关于在静态方法中创建的任何对象只属于该线程的声明是误导性的。无论方法是否是静态的,任何实例变量(非静态)都是线程安全的。静态方法只意味着代码是静态的;它没有提到变量。