Try finally vs using - C#
Формулировка задачи:
Всем привет, сегодня на работе обсуждали следующее:
Что лучше использовать?
п.с. при условии что метод Dispose не фаерит ошибку.
vs
//a,b,c,d is IDisposable
using(a)
using(b)
using(c)
using(d){
}//a,b,c,d is IDisposable
try{
}
finally{
if(a != null)
a.Dispose();
if(b != null)
b.Dispose();
if(c != null)
c.Dispose();
if(d != null)
d.Dispose();
}Решение задачи: «Try finally vs using»
textual
Листинг программы
void Main()
{
var disposable = new Disposable();
int testsCount = 1000000000;
using (new Diagnostics("using"))
{
for (int i = 0; i < testsCount; i++)
{
using (disposable)
using (disposable)
using (disposable)
using (disposable)
{
}
}
}
using (new Diagnostics("try"))
{
for (int i = 0; i < testsCount; i++)
{
try
{
}
finally
{
disposable?.Dispose();
disposable?.Dispose();
disposable?.Dispose();
disposable?.Dispose();
}
}
}
}
class Diagnostics : IDisposable
{
string _title;
Stopwatch _sw;
public Diagnostics(string title)
{
_title = title;
_sw = Stopwatch.StartNew();
}
public void Dispose()
{
_sw.Stop();
Console.WriteLine($"{_title} {_sw.ElapsedMilliseconds}");
}
}
class Disposable : IDisposable
{
public void Dispose()
{
}
}