Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
ReferenceBase.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using System.Threading;
5 
6 namespace SiliconStudio.Core
7 {
8  /// <summary>
9  /// Base class for a <see cref="IReferencable"/> class.
10  /// </summary>
11  public abstract class ReferenceBase : IReferencable
12  {
13  private int counter = 1;
14 
15  /// <inheritdoc/>
16  public int ReferenceCount { get { return counter; } }
17 
18  /// <inheritdoc/>
19  public virtual int AddReference()
20  {
21  int newCounter = Interlocked.Increment(ref counter);
22  if (newCounter <= 1) throw new InvalidOperationException(FrameworkResources.AddReferenceError);
23  return newCounter;
24  }
25 
26  /// <inheritdoc/>
27  public virtual int Release()
28  {
29  int newCounter = Interlocked.Decrement(ref counter);
30  if (newCounter == 0)
31  {
32  try
33  {
34  Destroy();
35  }
36  finally
37  {
38  // Reverse back the counter if there are any exceptions in the destroy method
39  Interlocked.Exchange(ref counter, newCounter + 1);
40  }
41  }
42  else if (newCounter < 0)
43  throw new InvalidOperationException(FrameworkResources.ReleaseReferenceError);
44  return newCounter;
45  }
46 
47  /// <summary>
48  /// Releases unmanaged and - optionally - managed resources
49  /// </summary>
50  protected abstract void Destroy();
51  }
52 }
Base interface for all referencable objects.
Definition: IReferencable.cs:8
virtual int Release()
Decrements the reference count of this instance. The method returns the new reference count...
Base class for a IReferencable class.
virtual int AddReference()
Increments the reference count of this instance. The method returns the new reference count...