是静态方法ASP.NET code-隐藏类非线程安全的? [英] Are static methods in ASP.NET code-behind classes non-thread-safe?
本文介绍了是静态方法ASP.NET code-隐藏类非线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以使用静态
在我的ASP.NET 页
和用户控件方法code>类,如果他们不使用任何实例成员?即:
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?
推荐答案
是的,你可以使用静态成员 - 他们是线程安全的。每个线程将在一个单独的上下文中执行,因此静态方法中创建的任何对象将只属于该线程。
Yes, you can use static members - 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.
您只需要当一个静态方法访问静态字段,如列表担心。但是,在你的例子中,code,绝对是线程安全的。
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.
这篇关于是静态方法ASP.NET code-隐藏类非线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文