Lean  $LEAN_TAG$
DisposableExtensions.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  *
15 */
16 
17 using System;
18 using QuantConnect.Logging;
19 
20 namespace QuantConnect.Util
21 {
22  /// <summary>
23  /// Provides extensions methods for <see cref="IDisposable"/>
24  /// </summary>
25  public static class DisposableExtensions
26  {
27  /// <summary>
28  /// Calls <see cref="IDisposable.Dispose"/> within a try/catch and logs any errors.
29  /// </summary>
30  /// <param name="disposable">The <see cref="IDisposable"/> to be disposed</param>
31  /// <returns>True if the object was successfully disposed, false if an error was thrown</returns>
32  public static bool DisposeSafely(this IDisposable disposable)
33  {
34  return disposable.DisposeSafely(error => Log.Error(error));
35  }
36 
37  /// <summary>
38  /// Calls <see cref="IDisposable.Dispose"/> within a try/catch and invokes the
39  /// <paramref name="errorHandler"/> on any errors.
40  /// </summary>
41  /// <param name="disposable">The <see cref="IDisposable"/> to be disposed</param>
42  /// <param name="errorHandler">Error handler delegate invoked if an exception is thrown
43  /// while calling <see cref="IDisposable.Dispose"/></param> on <paramref name="disposable"/>
44  /// <returns>True if the object was successfully disposed, false if an error was thrown or
45  /// the specified disposable was null</returns>
46  public static bool DisposeSafely(this IDisposable disposable, Action<Exception> errorHandler)
47  {
48  if (disposable == null)
49  {
50  return false;
51  }
52 
53  try
54  {
55  disposable.Dispose();
56  return true;
57  }
58  catch (ObjectDisposedException)
59  {
60  // we got what we wanted, the object has been disposed
61  return true;
62  }
63  catch (Exception error)
64  {
65  errorHandler(error);
66  return false;
67  }
68  }
69  }
70 }