0

Dispatcher.Invoke method can take either a Delegate or Action instance as a parameter. But Dispatcher.BeginInvoke method doesn't accept an Action instance; it supports only Delegate.

It forces me to cast a lambda expression to Action in case of BeginInvoke. For example:

Dispatcher.Invoke(() => Title = "foo"); // success
// Dispatcher.BeginInvoke(() => Title = "foo"); // error
Dispatcher.BeginInvoke((Action)(() => Title = "foo")); // success

Is there any reason why Dispatcher.BeginInvoke method couldn't take an Action parameter?

Shigure
  • 373
  • 4
  • 13
  • You'd have to ask the API designers to know for sure, no one else can tell. Maybe they just didn't think about it. That sucks, but you can define an extension method to circumvent it. – Lucas Trzesniewski Aug 09 '15 at 17:42
  • http://stackoverflow.com/questions/19009174/dispatcher-invoke-vs-begininvoke-confusion – sujith karivelil Aug 09 '15 at 17:42
  • Microsoft programmers started writing WPF code in June of 2002, .NET 1.0 was barely released. Nothing you can't fix with an extension method. – Hans Passant Aug 09 '15 at 18:17
  • You might want to use `Dispatcher.InvokeAsync` introduced in .Net 4.5. That should serve all your needs and makes live a bit easier. – gomi42 Aug 10 '15 at 15:03

1 Answers1

0

It's a design decision. Since WPF came with .NET 3.0 and probably WPF was developed during some years, maybe delegates like Action, Action<T>... or Func<T>... weren't added in early .NET 3.0 alphas so they left the code using their own delegate.

In the other hand, you argue you need to perform a cast while you should instantiate Action instead:

// This is possible!
Delegate d1 = new Action(() => Console.WriteLine("hello world"));

Dispatcher.BeginInvoke(new Action(() => { /* ---do stuff--- */ }));
Anouar khaldi
  • 772
  • 6
  • 15
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206