I just realized in a C# .Net 4.0 WPF background thread that this doesn't work (compiler error):
Dispatcher.Invoke(DispatcherPriority.Normal, delegate()
{
// do stuff to UI
});
From some examples I found out that it had to be casted like this: (Action)delegate()
. However, in other examples it is casted to other classes, e.g. System.Windows.Forms.MethodInvoker
.
Can anybody tell me what exactly is wrong with the example above? I also tried to reproduce it with other methods, but it was always working without casting:
delegate void MyAction();
void Method1(MyAction a) {
// do stuff
}
void Method2(Action a) {
// do stuff
}
void Tests()
{
Method1(delegate()
{
// works
});
Method2(delegate()
{
// works
});
Method1(() =>
{
// works
});
Method2(() =>
{
// works
});
Method2(new Action(delegate()
{
// works
}));
new System.Threading.Thread(delegate()
{
// works
}).Start();
}
So whats the best (most elegant, less redundant) way to invoke the Dispatcher, and whats so special with it that delegates must be casted?
I would like to point out even more cleaner code example to Svick's one, after all we all like one liners don't we?
Dispatcher.Invoke((Action) delegate { /* your method here */ });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With