ASP.NET代码后台类中的静态方法是否线程安全?

7

如果我的ASP.NET PagesUserControls类没有使用任何实例成员,我可以使用static方法吗?例如:

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;
    }
}

那么这个不是线程安全的吗?


“command”对象是什么类型的变量? - Kane
3个回答

9

是的,你可以使用静态方法 - 它们是线程安全的。每个线程将在单独的上下文中执行,因此在静态方法内创建的任何对象仅属于该线程。

只有当静态方法访问静态字段(如列表)时才需要担心。但在您的示例中,代码绝对是线程安全的。


我认为你的评论“你可以使用静态成员”是不正确的。 “成员”是指字段,属性或方法。因此,按照这个定义,静态成员(变量)和静态字段是相同的东西。也许你的意思是说可以使用静态方法。关于在静态方法中创建的任何对象仅属于该线程的说法是误导的。任何实例变量(非静态)都是线程安全的,无论方法是否为静态。静态方法只是意味着代码是静态的;它对变量没有任何影响。 - Matthew

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"。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接