use lambda expressions as parameter in Dispatcher.Invoke()
Asked Answered
B

2

9

I have such problem : there is some method

private List<int> GetStatusList()
        {
            return (List<int>)GetValue(getSpecifiedDebtStatusesProperty);
        }

To invoke it in main thread - I use

`delegate List<int> ReturnStatusHandler();` ...

this.Dispatcher.Invoke(new ReturnStatusHandler(GetStatusList));

How can I do the same, using lambda expression instead of custom delegate and method?

Ballot answered 10/10, 2011 at 8:54 Comment(1)
#4936959Certainly
G
15

you can pass this:

new Action(GetStatusList)

or

(Action)(() => { GetStatusList; })
Glucose answered 10/10, 2011 at 10:37 Comment(0)
M
7

You can avoid explicit casting by creating a simple method:

void RunInUiThread(Action action)
{
     Dispatcher.Invoke(action);
}

Use this as follows:

RunInUiThread(() =>
{
     GetStatusList();
});
Madelina answered 13/12, 2012 at 13:55 Comment(2)
Hi, i have 2 problems with your sample code. first, last line has a missing ')'. Second if i try your example i get an error, that for the non static field Dispatcher.Invoke(System.Action) a object reference is needed.Neva
Thanks I have applied correction to the above. Dispatcher is a non-static property on a DispatcherObject, which is the lowest base class of Control, Window, FrameworkElement etc. So you can only use Dispatcher in non-static contexts.Madelina

© 2022 - 2024 — McMap. All rights reserved.