我正在尝试只允许一个 Thread
访问一个非静态方法。我不会创建 Threads,而是使用 Tasks。我试图将该方法锁定为一个用途,但它并没有起作用,我首先尝试使用静态 Mutex
对象,然后是非静态的 Mutex
对象,但即使使用简单的监视器也不起作用。
我的代码:
private async void LoadLinkPreview()
{
try
{
// TODO: FEHLERTRÄCHTIG!
Monitor.Enter(_loadLinkMonitor);
Debug.WriteLine(DateTime.Now + ": Entered LinkPreview");
// Code ...
// There are also "await" usages here, don't know if this matters
}
catch { }
finally
{
Monitor.Exit(_loadLinkMonitor);
Debug.WriteLine(DateTime.Now + ": Left LinkPreview");
}
}
这是控制台显示的内容:
3/12/2013 6:10:03 PM: Entered LinkPreview
3/12/2013 6:10:05 PM: Entered LinkPreview
3/12/2013 6:10:05 PM: Left LinkPreview
3/12/2013 6:10:06 PM: Left LinkPreview
当然,有时它按照期望的顺序工作,但我希望它总是能够正常工作。也许有人可以帮助我吗?
编辑:我意识到控制台显示可能是期望的行为,因为“Left”的
WriteLine()
在退出监视器后,但现在我已经将它们切换了,并且可以确认肯定有两个线程同时工作!另外,控制台输出结果更加明显:3/12/2013 6:26:15 PM: Entered LinkPreview
3/12/2013 6:26:15 PM: Entered LinkPreview
2 had an error! // Every time the method is used I count up now, this confirms that the second
// time the method is called the error is produced, which would not happen if the monitor
// is working because I have an if statement right upfront ...
3/12/2013 6:26:17 PM: Left LinkPreview
3/12/2013 6:26:18 PM: Left LinkPreview