ASP.NET Thread Safety in aspx.cs code behind file
I am thinking of adding a DataContext as a member variable to my aspx.cs code-behind class for executing LinqToSql queries.
Is this thread safe? I am not sure if a new instance of this code-behind class is created for each HTTP request, or if the instance is shared amongst all request threads?
My fear is that I will get 10 simultaneous concurrent http requests that will be using the same database session.
public partial class MyPage : System.Web.UI.Page { private DataContext myDB = new DataContext(); protected void开发者_JAVA技巧 MyAction_Click(object sender, EventArgs e) { myDB.DoWork(); } }
The DataContext objects Thread Safety on MSDN is explained like this:
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Since your using a private member you have to consider your use in the class. As long as your not launching background threads and sharing the instance with you should have nothing to worry about.
The DataContext should be treated as resource and you may want to consider explicitly disposing of it as part of your class lifecycle. Its a light-weight enough object to consider putting in a using block for every operation too, depending on your use.. see the MSDN description:
a DataContext instance is designed to last for one "unit of work" however your application defines that term. A DataContext is lightweight and is not expensive to create. A typical LINQ to SQL application creates DataContext instances at method scope or as a member of short-lived classes that represent a logical set of related database operations.
It's safe because each time your page is loaded a new instance of MyPage
is created, thus a new instance of your DataContext
is also created.
There's no thread safety issue to worry about.
精彩评论