方法进入"最后"在等待结束之前

时间:2014-07-09 13:52:44

标签: c# multithreading async-await finally

我正在测试async / await,并且使用以下代码,它总是在“await”之后并且在它结束执行之前执行“finally”部分。

一旦进入“finally”,当尝试执行“Monitor.Exit(lockerObject);”时它会抛出SynchronizationLockException。

我知道这段代码不是async / await的“最佳实践”,而只是用于测试和理解它的行为。

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;
    }

知道这种行为的原因吗?

谢谢!

0 个答案:

没有答案