1
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
3
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
4
// software and associated documentation files (the "Software"), to deal in the Software
5
// without restriction, including without limitation the rights to use, copy, modify, merge,
6
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
7
// to whom the Software is furnished to do so, subject to the following conditions:
9
// The above copyright notice and this permission notice shall be included in all copies or
10
// substantial portions of the Software.
12
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
13
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
14
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
15
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
17
// DEALINGS IN THE SOFTWARE.
20
using System.Collections.Generic;
22
namespace ICSharpCode.NRefactory.Utils
25
/// This class is used to prevent stack overflows by representing a 'busy' flag
26
/// that prevents reentrance when another call is running.
27
/// However, using a simple 'bool busy' is not thread-safe, so we use a
28
/// thread-static BusyManager.
30
public static class BusyManager
32
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")]
33
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible",
34
Justification = "Should always be used with 'var'")]
35
public struct BusyLock : IDisposable
37
public static readonly BusyLock Failed = new BusyLock(null);
39
readonly List<object> objectList;
41
internal BusyLock(List<object> objectList)
43
this.objectList = objectList;
47
get { return objectList != null; }
52
if (objectList != null) {
53
objectList.RemoveAt(objectList.Count - 1);
58
[ThreadStatic] static List<object> _activeObjects;
60
public static BusyLock Enter(object obj)
62
List<object> activeObjects = _activeObjects;
63
if (activeObjects == null)
64
activeObjects = _activeObjects = new List<object>();
65
for (int i = 0; i < activeObjects.Count; i++) {
66
if (activeObjects[i] == obj)
67
return BusyLock.Failed;
69
activeObjects.Add(obj);
70
return new BusyLock(activeObjects);