views:

129

answers:

1

Hi,

I have a DirectoryMonitor class which works on another thread. It has the following events declared:

public class DirectoryMonitor
{
    public event EventHandler<MonitorEventArgs> CreatedNewBook;
    public event EventHandler ScanStarted;
    ....
}

public class MonitorEventArgs : EventArgs
{
    public Book Book { get; set; }
}

There is a form using that monitor, and upon receiving the events, it should update the display.

Now, this works:

    void DirectoryMonitor_ScanStarted(object sender, EventArgs e)
    {
        if (InvokeRequired)
        {
            Invoke(new EventHandler(this.DirectoryMonitor_ScanStarted));
        }
        else {...}
    }

But this throws TargetParameterCountException:

    void DirectoryMonitor_CreatedNewBook(object sender, MonitorEventArgs e)
    {
        if (InvokeRequired)
        {
            Invoke(new EventHandler<MonitorEventArgs>(this.DirectoryMonitor_CreatedNewBook));
        }
        else {...}
    }

What am I missing?

+2  A: 

The Invoke method excepts to receive a System.Delegate instance which can be invoked without passing any additional parameters. The delegate created by using DirectoryMonitor_ScanStarted requires 2 parameters and hence you get the exception when it's used.

You need to create a new delegate which wraps the call and arguments together.

MethodInvoker del = () => this.DirectoryMonitor_ScanStarted(sender,e);
Invoke(del);
JaredPar
Thanks for the solution. Though i still don't quite understand why the First event is fired OK, but the second ones throws the exception.
Am