使用 ObjectIDGenerator 类:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.objectidgenerator.aspx
引用:
ID 在 ObjectIDGenerator 实例的生命周期内是唯一的。
使用哈希表,ObjectIDGenerator 保留分配的 ID
到哪个对象。对象引用,它唯一地标识每个
对象,是运行时垃圾收集堆中的地址。目的
参考值可以在序列化过程中改变,但表是
自动更新,所以信息是正确的。
对象 ID 是 64 位数字。分配从一开始,所以零是
绝不是有效的对象 ID。格式化程序可以选择一个零值来
表示一个值为 null 的对象引用。
更新
这是解决问题的代码。在方面类中,使用以下内容:
public static ObjectIDGenerator ObjectIDGen = new ObjectIDGenerator();
然后:
bool firstTime;
long classInstanceID = ObjectIDGenerator.GetId(args.Instance, out firstTime);
更新
我想我会发布整个帖子所基于的代码。此代码有助于检测整个项目中的线程安全热点,如果多个线程访问同一个类实例时会触发警告。
如果您有 30k 行现有代码,并且想要添加更正式的线程安全验证(通常很难做到这一点),这很有用。它确实会影响运行时性能,因此您可以在调试模式下运行几天后将其删除。
要使用,请将 PostSharp + 此类添加到您的项目中,然后将方面“[MyThreadSafety]”添加到任何类。 PostSharp 将在每个方法调用之前将代码插入“OnEntry”中。方面传播到所有子类和子方法,因此您只需一行代码即可将线程安全检查添加到整个项目。
有关此技术的另一个实际应用示例,请参阅example designed to easily add caching to method calls。
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Text;
using System.Threading;
using MyLogType;
using PostSharp.Aspects;
using System.Collections.Concurrent;
using PostSharp.Extensibility;
namespace Demo
{
/// <summary>
/// Example code based on the page from a Google search of:
/// postsharp "Example: Tracing Method Execution"
/// </summary>
[Serializable]
public sealed class MyThreadSafetyCheck : OnMethodBoundaryAspect
{
/// <summary>
/// We need to be able to track if a different ThreadID is seen when executing a method within the *same* instance of a class. Its
/// ok if we see different ThreadID values when accessing different instances of a class. In fact, creating one copy of a class per
/// thread is a reliable method to fix threading issues in the first place.
///
/// Key: unique ID for every instance of every class.
/// Value: LastThreadID, tracks the ID of the last thread which accessed the current instance of this class.
/// </summary>
public static ConcurrentDictionary<long, int> DetectThreadingIssues = new ConcurrentDictionary<long, int>();
/// <summary>
/// Allows us to generate a unique ID for each instance of every class that we see.
/// </summary>
public static ObjectIDGenerator ObjectIDGenerator = new ObjectIDGenerator();
/// <summary>
/// These fields are initialized at runtime. They do not need to be serialized.
/// </summary>
[NonSerialized]
private string MethodName;
[NonSerialized]
private long LastTotalMilliseconds;
/// <summary>
/// Stopwatch which we can use to avoid swamping the log with too many messages for threading violations.
/// </summary>
[NonSerialized]
private Stopwatch sw;
/// <summary>
/// Invoked only once at runtime from the static constructor of type declaring the target method.
/// </summary>
/// <param name="method"></param>
public override void RuntimeInitialize(MethodBase method)
{
if (method.DeclaringType != null)
{
this.MethodName = method.DeclaringType.FullName + "." + method.Name;
}
this.sw = new Stopwatch();
this.sw.Start();
this.LastTotalMilliseconds = -1000000;
}
/// <summary>
/// Invoked at runtime before that target method is invoked.
/// </summary>
/// <param name="args">Arguments to the function.</param>
public override void OnEntry(MethodExecutionArgs args)
{
if (args.Instance == null)
{
return;
}
if (this.MethodName.Contains(".ctor"))
{
// Ignore the thread that accesses the constructor.
// If we remove this check, then we get a false positive.
return;
}
bool firstTime;
long classInstanceID = ObjectIDGenerator.GetId(args.Instance, out firstTime);
if (firstTime)
{
// This the first time we have called this, there is no LastThreadID. Return.
if (DetectThreadingIssues.TryAdd(classInstanceID, Thread.CurrentThread.ManagedThreadId) == false)
{
Console.Write(string.Format("{0}Error E20120320-1349. Could not add an initial key to the \"DetectThreadingIssues\" dictionary.\n",
MyLog.NPrefix()));
}
return;
}
int lastThreadID = DetectThreadingIssues[classInstanceID];
// Check 1: Continue if this instance of the class was accessed by a different thread (which is definitely bad).
if (lastThreadID != Thread.CurrentThread.ManagedThreadId)
{
// Check 2: Are we printing more than one message per second?
if ((sw.ElapsedMilliseconds - this.LastTotalMilliseconds) > 1000)
{
Console.Write(string.Format("{0}Warning: ThreadID {1} then {2} accessed \"{3}\". To remove warning, manually check thread safety, then add \"[MyThreadSafetyCheck(AttributeExclude = true)]\".\n",
MyLog.NPrefix(), lastThreadID, Thread.CurrentThread.ManagedThreadId, this.MethodName));
this.LastTotalMilliseconds = sw.ElapsedMilliseconds;
}
}
// Update the value of "LastThreadID" for this particular instance of the class.
DetectThreadingIssues[classInstanceID] = Thread.CurrentThread.ManagedThreadId;
}
}
}
我可以按需提供完整的演示项目。