简体   繁体   English

ASP.NET 代码隐藏类中的静态方法是非线程安全的吗?

[英]Are static methods in ASP.NET code-behind classes non-thread-safe?

Can I use static methods in my ASP.NET Pages and UserControls classes if they don't use any instance members?如果 ASP.NET PagesUserControls类不使用任何实例成员,我可以在它们中使用static方法吗? Ie: IE:

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?或者这不是线程安全的?

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.但是在您的示例中,代码绝对是线程安全的。

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...除非您访问其他静态方法有机会与其同时执行的静态成员......

it is.这是。 The only thing to worry about in your context about thread-safeness is a concept that involves static members, as already said.如前所述,在您的上下文中唯一需要担心的关于线程安全的概念是涉及静态成员的。 When any method (static or not) accesses a static member, you should worry about multithreading issues.当任何方法(静态或非静态)访问静态成员时,您应该担心多线程问题。 Consider the following:考虑以下:

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());

The answer is: It may be "42, 43, 0", "42, 0, 1" you wont know before..答案是:它可能是你以前不知道的“42, 43, 0”,“42, 0, 1”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM