COMException occurred in IConnectionPoint Unadvise()

0

I'm developing a program that checks if the Windows Form application is connected to the internet or not.

I based my code from the following link:

https://www.codeproject.com/Articles/34650/How-to-use-the-Windows-NLM-API-to-get-notified-of

I'm getting this System.Runtime.InteropServices.COMException in the Unadvise() method of class IConnectionPoint and I'm not sure as to why.

Here is the additional information of the exception:

There is no connection for this connection ID (Exception from HRESULT: 0x80040004 (OLE_E_NOCONNECTION))

Here is the method where Advise() is called:

private INetworkListManager nlm;
private IConnectionPoint icp;
private int cookie = 0;

public void AdviseNetworkListManager()
{
    try
    {
        IConnectionPointContainer icpc = (IConnectionPointContainer)nlm;
        Guid guid = typeof(INetworkListManagerEvents).GUID;
        icpc.FindConnectionPoint(ref guid, out icp);
        icp.Advise(this, out cookie);
    }
    catch (Exception e)
    {
        throw new Exception(e.Message);
    }
}

And here is the method where Unadvise() is called:

public void UnadviseNetworkListManager()
{
    icp.Unadvise(cookie);
}

And here is the constructor and event that calls both the above methods:

private NetworkHelper netHelper;

public SQLiteForm()
{
    InitializeComponent();
    SQLiteDatabase.ConnectDB();
    DBHelper.ConnectDB();
    netHelper = new NetworkHelper();
    netHelper.AdviseNetworkListManager();
    netHelper.DoBackgroundWork += backgroundWorker_DoWork;
}

private void SQLiteForm_FormClosing(object sender, FormClosingEventArgs e)
{
    netHelper.UnadviseNetworkListManager();
    DBHelper.DisconnectDB();
    SQLiteDatabase.DisconnectDB();
    Application.Exit();
}

Does anyone know as to why I'm getting this exception?

c#
.net
winforms
interop
comexception
asked on Stack Overflow Jun 23, 2017 by Stanley Yu • edited Jun 27, 2017 by Stanley Yu

1 Answer

0

I see what's the problem now!

Upon debugging, I've noticed that when Application.Exit() is executed, it calls the SQLiteForm_FormClosing event again. Since the Unadvise() is already executed, it throws the OLE_E_NOCONNECTION exception.

I have solved this by moving the Application.Exit() to the SQLiteForm_FormClosed event as such:

private void SQLiteForm_FormClosed(object sender, FormClosedEventArgs e)
{
    Application.Exit();
}

That way it won't call the SQLiteForm_FormClosing event anymore since the form is already closed.

answered on Stack Overflow Jun 27, 2017 by Stanley Yu

User contributions licensed under CC BY-SA 3.0