|
| 1 | +/***************************************************************************** |
| 2 | + Copyright 2018 The TensorFlow.NET Authors. All Rights Reserved. |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +******************************************************************************/ |
| 16 | + |
| 17 | +using System; |
| 18 | +using System.Runtime.InteropServices; |
| 19 | + |
| 20 | +namespace Tensorflow.Util |
| 21 | +{ |
| 22 | + internal static class SafeHandleExtensions |
| 23 | + { |
| 24 | + /// <summary> |
| 25 | + /// Acquires a lease on a safe handle. This method is intended to be used in the initializer of a <c>using</c> |
| 26 | + /// statement. |
| 27 | + /// </summary> |
| 28 | + /// <param name="handle">The <see cref="SafeHandle"/> to lease.</param> |
| 29 | + /// <returns>A <see cref="SafeHandleLease"/>, which must be disposed to release the resource.</returns> |
| 30 | + /// <exception cref="ObjectDisposedException">If the lease could not be acquired.</exception> |
| 31 | + public static SafeHandleLease Lease(this SafeHandle handle) |
| 32 | + { |
| 33 | + if (handle is null) |
| 34 | + throw new ArgumentNullException(nameof(handle)); |
| 35 | + |
| 36 | + var success = false; |
| 37 | + try |
| 38 | + { |
| 39 | + handle.DangerousAddRef(ref success); |
| 40 | + if (!success) |
| 41 | + throw new ObjectDisposedException(handle.GetType().FullName); |
| 42 | + |
| 43 | + return new SafeHandleLease(handle); |
| 44 | + } |
| 45 | + catch |
| 46 | + { |
| 47 | + if (success) |
| 48 | + handle.DangerousRelease(); |
| 49 | + |
| 50 | + throw; |
| 51 | + } |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments