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 {...}
}
开发者_如何学GoWhat am I missing?
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);
You're missing the parameters:-
void DirectoryMonitor_ScanStarted(object sender, MonitorEventArgs e)
{
if (InvokeRequired)
{
Invoke(new EventHandler<MonitorEventArgs>(DirectoryMonitor_ScanStarted), sender, e);
}
else {...}
}
For reasons not clear to me (probably due to COM legacy) it's permissible to omit parameters when using a generic event, but not when using a user defined EventArg type.
精彩评论