I am trying to only allow one Thread
to access a non-static method from an object
. I don't really create Threads but use Tasks instead. I tried to lock the method down to one usage but it just isn't working, I first tried it with a static Mutex
object, then a non-static Mutex
object but even with a simple monitor it's not working.
My code:
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");
}
}
and this is what the Console displays:
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
Of course sometimes it works in the wanted order but I want it to always work. Can someone help me maybe?
EDIT: I realized that the console display could be wanted behavior, since the "Left" WriteLine()
is after the monitor has been exited, but I switched them now and can confirm that there are definitely two threads working at the same time! Also a more obvious console result:
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