假设我有以下代码(请假设所有适当的导入语句):
public class CTestClass {
// Properties
protected Object LockObj;
public ConcurrentDictionary<String, String> Prop_1;
protected System.Timers.Timer TImer_1;
// Methods
public CTestClass () {
LockObj = new Object ();
Prop_1 = new ConcurrentDictionary<String, String> ();
Prop_1.TryAdd ("Key_1", "Value_1");
Timer_1 = new System.Timers.Timer ();
Timer_1.Interval = (1000 * 60); // One minute
Timer_1.Elapsed += new ElapsedEventHandler ((s, t) => Method_2 ());
Timer_1.Enabled = true;
} // End CTestClass ()
public void Method_1 () {
// Do something that requires Prop_1 to be read
// But *__do not__* lock Prop_1
} // End Method_1 ()
public void Method_2 () {
lock (LockObj) {
// Do something with Prop_1 *__only if__* Method_1 () is not currently executing
}
} // End Method_2 ()
} // End CTestClass
// Main class
public class Program {
public static void Main (string[] Args) {
CTestClass TC = new CTestClass ();
ParallelEnumerable.Range (0, 10)
.ForAll (s => {
TC.Method_1 ();
});
}
}
我知道可以使用 MethodBase.GetCurrentMethod,但是(没有对全局变量进行混乱的簿记)是否可以在不反思的情况下解决问题?
提前感谢你的帮助。
编辑
(a) 更正了 LockObj 范围的错误
(b)通过解释添加更多内容(摘自我下面的评论)
我已经更正了我的代码(在我的实际项目中)并将 LockObj 作为类属性。问题是,Method_2 实际上是由 System.Timers.Timer 触发的,当它准备触发时,Method_1 很可能已经在执行。但在这种情况下,重要的是等待 Method_1 完成执行,然后再继续 Method_2。
我同意我试图创建的最小工作示例并没有明确后一点。让我看看我是否可以编辑 MWE。
代码编辑完成
最终编辑
我正在使用 Visual Studio 2010 和 .NET 4.0,所以我没有可以让我的生活更轻松的异步/等待功能。