我试图只允许一个人Thread
从object
. 我并没有真正创建线程,而是使用任务。我试图将该方法锁定为一种用法,但它不起作用,我首先尝试使用静态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
当然,有时它会按照想要的顺序工作,但我希望它始终有效。有人可以帮助我吗?
编辑:我意识到控制台显示可能是想要的行为,因为“左”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