How to avoid Safe handle has been closed
Asked Answered
C

1

6

I have the following code in a test:

 private void LoadIncomeStatementViewModel()
    {
        using (var evt = new AutoResetEvent(false))
        {
            EventHandler handler = (sender, e) => evt.Set();

            _incomeStatementViewModel.Loaded -= handler;
            _incomeStatementViewModel.Loaded += handler;
            _incomeStatementViewModel.LoadDataCommand.Execute(null);
            evt.WaitOne();
        }
    }

Now if I run the following test

[Test]
public void Test()
{
   LoadIncomeStatementViewModel();
   // do something

   LoadIncomeStatementViewModel();
   // do something
}

The second time the LoadIncomeStatementViewModel() is called I get a "Safe handle has been disposed" error message at EventHandler handler = (sender, e) => evt.Set();

Surely the using statement has reinitialized evt when the method is rerun the second time. I have a feeling that this may be something to do with the Resharper Test Runner (Nunit 2.7).

Clermontferrand answered 9/9, 2010 at 23:53 Comment(0)
S
4

You need to unlink the handler as below. Otherwise in the second run you were receiving the first instance.

private void LoadIncomeStatementViewModel()
{
    using (var evt = new AutoResetEvent(false))
    {
        EventHandler handler = (sender, e) => evt.Set();

        try
        {
            _incomeStatementViewModel.Loaded += handler;
            _incomeStatementViewModel.LoadDataCommand.Execute(null);
            evt.WaitOne();
        }
        finally
        {
            _incomeStatementViewModel.Loaded -= handler;
        }
    }
}
Sayers answered 3/1, 2013 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.