I´m testing async/await, and with the following code, it always execute the "finally" section just after the "await" and before it ends its execution.
And once inside the "finally", when attempt to execute the "Monitor.Exit(lockerObject);" it throws a SynchronizationLockException.
I know this code is not a "best practice" for async/await, but is just for testing and understanding its behaviour.
private async void button1_Click(object sender, EventArgs e)
{
new Thread(new ThreadStart(test)).Start();
}
private async void test()
{
var v = await camIp.SendMessageAsync(new ComMessage(CameraIPConst.CMD_MOVE_UP));
Console.WriteLine("END");
}
public async Task<IViewAppMessage> SendMessageAsync(ComMessage message)
{
IViewAppMessage response = null;
if (!String.IsNullOrEmpty(message.Command))
{
if (Monitor.TryEnter(lockerObject, 500))
{
try
{
if (!blocked)
{
blocked = true;
switch (message.Command)
{
case CameraIPConst.CMD_MOVE_UP:
response = await camera.sendCommandAsync(new byte[] { 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x01 });
break;
}
blocked = false;
}
Console.WriteLine("Fuera ");
}
catch { throw; }
finally {
try
{
Monitor.Exit(lockerObject);
}
catch { throw; }
}
}
}
return response;
}
Any idea why this behaviour?
Thanks!