Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid Safe handle has been closed

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).

like image 651
Jeremy Holt Avatar asked Oct 25 '22 07:10

Jeremy Holt


1 Answers

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;
        }
    }
}
like image 148
dperez Avatar answered Nov 15 '22 05:11

dperez