PDA

View Full Version : سوال: using



arash691
پنج شنبه 08 فروردین 1392, 17:48 عصر
سلام دوستان ...

چرا بعضی از دستورات رو داخل using مینویسن ؟ بطور مثال به دستور زیر نگاه کنید :


string connection_string = "Data Source=.\\sqlexpress;Integrated Security =yes;";

using ( SqlConnection con =new SqlConnection(connection_string))

{
string Database_Name = textBox1.Text;
SqlCommand com = new SqlCommand("Create DataBase [" + Database_Name + "];", con);
com.Connection.open();
com.ExecuteNonQuery();

}
خب همینطور که میبینید دستورات بالا یک پایگاه داده با نامی که از کاربر میگیره یعنی DataBase_Name بوجود میاره ... ولی سوال اصلی من اینه که چرا دستورات رو درون بدنه using نوشته و اینکه وقتی اینطوری دستورات رو مینویسیم چه تفاوتی با حالتی که از using استفاده نکنیم داره ؟

ali ghaemi
پنج شنبه 08 فروردین 1392, 18:27 عصر
اولا توجه داشته باشید کلاسی که در جلوی عبارت Using قرار می گیره باید رابط IDisposable را پیاده سازی کرده باشه در واقع دارید به کامپایلر می گید که بعد از اجراء بلوک Using حافظه تخصیص یافته به کلاس مربوطه (sqlconnection ) را آزاد کند حتی اگر در اجراء دستورات داخل بلوک خطایی پیش آمد



C#‎, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.
The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.
A using statement can be exited either when the end of the using statement is reached or if an exception is thrown and control leaves the statement block before the end of the statement